【问题标题】:letter getting cutt off when I use a counter in do while loop c++当我在 do while loop c++​​ 中使用计数器时,字母被截断
【发布时间】:2015-04-22 05:44:30
【问题描述】:

我试图在我的 do while 循环中使用一个计数器,但如果我这样做了,它会在第一次迭代中切断我的 getline 的第一个字母

这里是 do while 循环..

do
{
    cout << "Enter the name of your class: " << endl;
    cin.get();
    getline(cin, classnames[i]);

    cout << "Enter how many units was the class: " << endl;
    cin >> classunits[i];

    cout << "Enter the grade you completed the class with: " << endl;
    cin >> classgrades[i];
    classgrades[i] = toupper(classgrades[i]);

    i++;

} while (again());

例如,如果我输入 english,'e' 将在第一次迭代中被切断,但任何下一次迭代 english 都会显示正常。

只有当我添加i++时才会发生这种情况

我已经尝试过cin.ignore(),但我似乎仍然无法破解它!

【问题讨论】:

  • 好吧cin.get() 读取一个字符。大概就是这样。
  • 你为什么用这个cin.get()?它只是读取一个字符并丢弃它
  • hm 当我删除它时,它会在循环时显示输入名称/输入多少单位。对不起,我还是很新哈哈

标签: c++ arrays increment getline


【解决方案1】:

去掉开头的cin.get(),最后加上cin.ignore():

do
{
    cout << "Enter the name of your class: " << endl;
    // cin.get();  // remove
    getline(cin, classnames[i]);

    cout << "Enter how many units was the class: " << endl;
    cin >> classunits[i];

    cout << "Enter the grade you completed the class with: " << endl;
    cin >> classgrades[i];
    classgrades[i] = toupper(classgrades[i]);

    cin.ignore(); // add
    i++;

} while (again());

【讨论】:

  • 嘿,是的,谢谢,现在我这样做了
  • @noobex: 你的again 函数是做什么的?
  • 它会询问用户是否愿意为他们参加的另一堂课再次重复所有这些。看着那个函数,我发现它还需要一个 cin,ignore();谢谢您的帮助 !! :)
  • @noobex:我问过这个问题,因为again() 函数可能会在输入流中留下一些东西,并可能损害循环中的输入(其中getline 读取类名的名称)...所以,请考虑在again 正文的最后(return 之前)重复cin.ignore()。
【解决方案2】:

正如其他人所提到的,cin.get() 提取并返回输入流中您要丢弃的第一个字符。

http://www.cplusplus.com/reference/istream/istream/get/

【讨论】:

    【解决方案3】:

    删除cin.get();。它会读取您输入的第一个字符,甚至不会将其存储在任何地方,因此您输入的第一个字符不会存储在字符串中。

    【讨论】:

      猜你喜欢
      • 2020-11-02
      • 1970-01-01
      • 2014-01-11
      • 1970-01-01
      • 2013-12-26
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多