【问题标题】:Why the first character is skipped in 2nd iterations onwards为什么在第二次迭代中跳过第一个字符
【发布时间】:2019-01-14 04:23:15
【问题描述】:

代码部分:

 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;
}

Output

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.ignore() 则输入不正确,所以我应该怎么做才能在每次迭代中输入。

标签: getline


【解决方案1】:

cin&gt;&gt;t; 从用户那里读取一个数字。因为用户必须在数字后按回车,所以您需要 cin.ignore() 来忽略换行符。但是,在循环中,您使用getline,它读取整行。没有什么可以忽略的,因为您已经阅读了整行。所以你需要将cin.ignore() 移动到循环之前

就个人而言,我更喜欢总是从用户那里读取行,因为这是我希望用户输入的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 2013-10-03
    • 2020-11-14
    • 1970-01-01
    • 2011-08-08
    • 1970-01-01
    • 2016-10-22
    相关资源
    最近更新 更多