我正在完成一项实验室作业,系统会提示用户输入他们希望订购的鱼的类型并输入每磅的价格。在报告打印之前,需要两次提示用户输入鱼的类型和价格。
问题是程序在循环的第一个实例完成之前就结束了。 (代码的编写方式报告上的标题将打印两次,但那是在说明中。)
代码如下,非常感谢任何帮助。
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
float price;
string fishType;
int counter = 0;
// Change the console's background color.
system ("color F0");
while (counter < 3){
// Collect input from the user.
cout << "Enter the type of seafood: ";
cin >> fishType; // <------ FAILS AT THIS POINT. I GET THE PROMPT AND AT THE "ENTER" IT DISPLAYS THE REPORT
cout << "Enter the price per pound using dollars and cents: ";
cin >> price;
counter++;
}
// Display the report.
cout << " SEAFOOD REPORT\n\n";
cout << "TYPE OF PRICE PER" << endl;
cout << "SEAFOOD POUND" << endl;
cout << "-------------------------------" << endl;
cout << fixed << setprecision(2) << showpoint<< left << setw(25)
<< fishType << "$" << setw(5) << right << price << endl;
cout << "\n\n";
system ("pause");
return 0;
}
最佳答案
使用std::istream::operator>>(float)
,读取不会消耗换行符, 价格
:
cin >> price; // this will not consume the new line character.
下一次读取时出现换行符,使用operator>>(std::istream, std::string)
), 进入fishType
:
cin >> fishType; // Reads a blank line, effectively.
然后本应成为下一个 fishType
的用户输入将被 price
读取(并且失败),因为它不是有效的 float
值。
更正,ignore()
直到读取 price
后的下一个换行符。像这样的东西:
cin.ignore(1024, '\n');
// or: cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
始终检查输入操作的状态以确定它们是否成功。这很容易实现:
if (cin >> price)
{
// success.
}
如果 fishType
可以包含空格,那么使用 operator>>(std::istream, std::string)
是不合适的,因为它会在第一次读取时停止空格。使用 std::getline()
相反:
if (std::getline(cin, fishType))
{
}
当用户输入一个换行符时,将写入stdin
,即cin
:
cod\n 1.9\n salmon\n 2.7\n
On first iteration of the loop:
cin >> fishType; // fishType == "cod" as operator>> std::string
// will read until first whitespace.
和 cin
现在包含:
\n 1.9\n salmon\n 2.7\n
then:
cin >> price; // This skips leading whitespace and price = 1.9
和 cin
现在包含:
\n salmon\n 2.7\n
then:
cin >> fishType; // Reads upto the first whitespace
// i.e reads nothin and cin is unchanged.
cin >> price; // skips the whitespace and fails because
// "salmon" is not a valid float.
关于c++ - 第一次尝试时循环失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14991661/