C++ 使用getline时调用terminate

C++ 使用getline时调用terminate,c++,C++,我在运行时遇到此错误- terminate在抛出'std::out_of_range'what():basic_string::substr'实例后调用 如在后()中建议的,在C++中读取一行,我们使用 STD::GETLIN(STD:CIN,name);我的代码是: int t; cin>>t; while(t--) { string s; int num; getline(std::cin,s);

我在运行时遇到此错误-

terminate在抛出'std::out_of_range'what():basic_string::substr'实例后调用
如在后()中建议的,在C++中读取一行,我们使用<代码> STD::GETLIN(STD:CIN,name);<代码>我的代码是:

   int t;
    cin>>t;
    while(t--)
    {
        string s;
        int num;
        getline(std::cin,s);
        string q= s.substr(0,3);
        num  =stoi(s.substr(4));
    }
当我只运行此选项时:

    string s;
    int num;
    getline(std::cin,s);
    string q= s.substr(0,3);
    num  =stoi(s.substr(4));

它起作用了。我想我得冲掉我的cin缓冲液。对于这些类型的案例,最佳实践应该是什么?提前感谢

对于
>t
的最佳实践是在之后刷新输入缓冲区,例如通过
忽略
substr
的最佳实践是首先确保字符串长度。是的,在while循环之后,我写
std::cin.ignore(INT_MAX)时它工作正常。所以每次我都应该这样写吗?没有更好的方法吗?通常你只想通过格式化数字输入后留下的换行符来使用<代码>标准::cin.ignore(标准::数值限制::max(),'\n')
>t
的最佳做法是在之后刷新输入缓冲区,例如通过
忽略
substr
的最佳实践是首先确保字符串长度。是的,在while循环之后,我写
std::cin.ignore(INT_MAX)时它工作正常。所以每次我都应该这样写吗?没有更好的方法吗?通常你只想通过格式化数字输入后留下的换行符来使用<代码>标准::cin.ignore(标准::数值限制::max(),'\n')详细讨论。