關於cin,getline一起出現無法正常輸入的問題
阿新 • • 發佈:2018-03-21
words log () inpu time ctrl+z color clear 文件
int N; char c; int num=0; string s; cin>>N>>c; getline(cin,s,‘\n‘); for(int i=0; s[i]!=‘\0‘;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<<"\nNow you can input as many words as you can. If you want to terminate, you may press Ctrl+z:\n";
while (cin >> word)
cout << word << endl;
cin.clear();//調用clear()來清除cin的狀態
string line;
// read line at time until end-of-file
cout<<"\nNow you can input as many lines of words as you wish. To terminate, please press Ctrl+z:\n";
while (getline(cin, line))
cout << line << endl;
cin.clear();
keep_window_open();
關於cin,getline一起出現無法正常輸入的問題