为什么cin >>(string)在cin >>(int)失败后停止了?

lst*_*lst 2 c++ cin

当调用cin >>(int)和cin >>(string)时,当第一个输入对整数不正确时,似乎cin >>(string)将无法检索第二个输入,即使它是正确的字符串.

源代码很简单:

cout<<"Please enter count and name"<<endl;;
int count;
cin>>count;     // >> reads an integer into count
string name;
cin>>name;      // >> reades a string into name

cout<<"count: "<<count<<endl;
cout<<"name: "<<name<<endl;
Run Code Online (Sandbox Code Playgroud)

测试用例是:

情况1:键入字符(不适合int)和字符

请输入计数和名称

广告

数:0

名称:

案例2:键入数字和字符

请输入计数和名称

30广告

数:30

名称:广告

案例3:键入数字和数字(可以作为字符串)

请输入计数和名称

20 33

数:20

名称:33

Ste*_*ner 5

流有一个内部错误标志,一旦设置,它将保持设置状态,直到您明确清除它为止.当读取失败时,例如因为输入无法转换为所需类型,则会设置错误标志,并且只要您不清除此标志,就不会尝试任何后续读取操作:

int main() {

    stringstream ss("john 123");

    int testInt;
    string testString;

    ss >> testInt;
    if (ss) {
        cout << "good!" << testInt << endl;
    } else {
        cout << "bad!" << endl;
    }

    ss >> testString;
    if (ss) {
        cout << "good!" << testString << endl;
    } else {
        cout << "bad!" << endl;
    }

    ss.clear();
    ss >> testString;
    if (ss) {
        cout << "good:" << testString << endl;
    } else {
        cout << "bad!";
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

bad!
bad!
good:john
Run Code Online (Sandbox Code Playgroud)