关于cin,getline一起出现无法正常输入的问题

int N;
    char c;
    int num=0;
    string s;
     cin>>N>>c;

     getline(cin,s,'
');
     for(int i=0; s[i]!='';i++)
     {
         num++;
     }
     cout<<num<<endl;

这时cin(输入流)的状态被标志为遇到文件结尾,如果不调用in.clear()或其他可以清除流的状态的函数来将清除cin的状态,则cin被标志为遇到文件结尾的状态一起保持。到第二个 getline(cin, line)再次引用cin,则此时的cin的状态为遇到文件结束标志,无法输入,因此num始终为0;

一.调用clear()来清除cin的状态

二.cin.flush();

三.cin.ignore();

总有一款适合你……尝试了好多次,终于可以了!

string word;
// read until end-of-file, writing each word to a new line
cout<<" Now you can input as many words as you can. If you want to terminate, you may press Ctrl+z: ";
while (cin >> word)
cout << word << endl;

cin.clear();//调用clear()来清除cin的状态

string line;
// read line at time until end-of-file
cout<<" Now you can input as many lines of words as you wish. To terminate, please press Ctrl+z: ";
while (getline(cin, line))
cout << line << endl;
cin.clear();

keep_window_open();

原文地址:https://www.cnblogs.com/lyqf/p/8614359.html