代码部分:
int t;
cout<<"Enter a no.";
cin>>t;
while(t--){
cout<<"Enter a string :"<<endl;
string str;
cin.ignore();
getline(cin,str);
cout<<"You entered :"<<str<<endl<<endl;
}
Enter a no. 3
Enter a string :
It is working
You entered :It is working
Enter a string :
It is working
You entered :t is working
Enter a string :
It is working
You entered :t is working
为什么在第二次迭代中跳过第一个字符。任何帮助将受到欢迎。
所述cin>>t;
读取来自用户的数目。因为用户必须在数字后按回车键,所以您需要cin.ignore()
忽略换行符。但是,在循环中,您使用getline
,它读取整行。没有什么可忽略的,因为您已经阅读了整行。所以你需要在循环之前移动cin.ignore()
to 。
就个人而言,我更喜欢始终从用户那里读取行,因为这是我希望用户输入的内容。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句