【问题标题】:Why are my inputs being skipped by the compiler?为什么编译器会跳过我的输入?
【发布时间】:2021-03-12 18:15:40
【问题描述】:

我对 C++ 编程比较陌生,而且因为我的学校教学大纲在 2 年前放弃了它,所以我最近开始自学它,所以我是个菜鸟。在程序中,我正在向用户输出正确输入数据的指示,但是在运行时,编译器只显示输出并获取第一行的输入。其他两个被跳过,光标直接转到最后一行。编译器没有给我任何错误。我也尝试在每一行后面加上 endl。

double picLen, picWid, colorPrice, perimeterOfFrame, area, total, framePrice ;
char frameType, color, crown, crownAmount ; 

//inputs//
cout << "Enter the length and width (in inches) of the picture : " ;
cin >> picLen, picWid ;
cout << endl ;
cout << "Enter the type of frame ('r' for regular, 'f' for fancy) : " ;
cin >> frameType ;
cout << endl ;
cout << "Choose the color (enter first letter of color name) : " ;
cin >> color ;
cout << endl ;
cout << "Do you want crowns on the sides? ('y' for yes and 'n' for no) : " ;
cin >> crown ;
cout << endl << endl ;

cout << fixed << showpoint << setprecision(2);

【问题讨论】:

  • 读取一行输入后,调用getchar(),可能是行尾字符的问题。
  • 第一个问题:cin &gt;&gt; picLen, picWid 应该是cin &gt;&gt; picLen &gt;&gt; picWid

标签: c++ user-input


【解决方案1】:

他们在初学者 C 和 C++ 教程中经常忽略的一件事是,当您按下 Enter 时,输入流中会添加一个额外的字符。

如果您不手动删除此“行尾”(\n) 字符,它可能会弄乱您的其他输入操作。

C++ 有一个方法可以做到这一点:

cin.ignore(numeric_limits<streamsize>::max(), '\n');

这将抛出任何未处理的字符,直到遇到行尾,然后它会抛出行尾并停止,因此您可以再次调用cin &gt;&gt; myNextVar

如果您觉得numeric_limits&lt;streamsize&gt;::max() 看起来很吓人,现在只需将其替换为任何大数字,例如 256。 它只是说要忽略多少个字符。 通常,您只需要忽略一个,但最好清除所有内容以防万一。

更多信息在这里:https://www.cplusplus.com/reference/istream/istream/ignore/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-14
    • 1970-01-01
    • 2017-05-02
    • 2021-08-06
    • 1970-01-01
    • 2016-07-18
    • 1970-01-01
    • 2020-06-03
    相关资源
    最近更新 更多