为什么编译器会跳过我的输入?

时间:2021-03-12 18:15:40

标签: c++ user-input

我对 C++ 编程还比较陌生,因为我的学校教学大纲在 2 年前放弃了它,我最近开始自己自学,所以我是个菜鸟。在程序中,我向用户输出正确输入数据的指示,但是在运行时,编译器只显示输出并接受第一行的输入。其他两个被跳过,光标直接移动到最后一个 cout 行。编译器没有给我任何错误。我也试过在每一行后加上 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);

1 个答案:

答案 0 :(得分:0)

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

如果您不手动去掉这个“行尾”(\n) 字符,它可能会扰乱您的其他输入操作。

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

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

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

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

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