1

我正在完成一项实验室任务,如果用户想要订购鱼,系统会提示他们输入类型,并输入每磅的价格。在打印报告之前,需要两次提示用户输入鱼的类型和价格。

问题是程序在循环的第一个实例完成之前结束。(代码的编写方式报告上的标题将打印两次,但那是在说明中。)

代码如下,非常感谢任何帮助。

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

1 回答 1

7

新行字符不会被读取,使用std::istream::operator>>(float),消耗price

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

如果fishTypecan 包含空格,则 usingoperator>>(std::istream, std::string)不合适,因为它将在第一个空格处停止读取。改用std::getline()

if (std::getline(cin, fishType))
{
}

当用户输入时,将写入一个换行符stdin,即cin

鳕鱼\n
1.9\n
三文鱼\n
2.7\n

在循环的第一次迭代中:

cin >> fishType; // fishType == "cod" as operator>> std::string
                 // will read until first whitespace.

现在cin包含:

\n
1.9\n
三文鱼\n
2.7\n

然后:

cin >> price; // This skips leading whitespace and price = 1.9

现在cin包含:

\n
三文鱼\n
2.7\n

然后:

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.
于 2013-02-20T23:13:29.093 回答