第一次尝试时循环失败

Kev*_*ltz 1 c++

我正在完成一个实验室作业,如果他们想要订购鱼类,则提示用户输入类型并输入每磅价格.在报告打印之前,需要提示用户输入鱼的类型和价格两次.

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

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

#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;
}
Run Code Online (Sandbox Code Playgroud)

hmj*_*mjd 7

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

cin >> price; // this will not consume the new line character.
Run Code Online (Sandbox Code Playgroud)

在下次读取时使用新行字符的存在operator>>(std::istream, std::string),进入fishType:

cin >> fishType; // Reads a blank line, effectively.
Run Code Online (Sandbox Code Playgroud)

然后,由于它不是有效值,因此将fishType读取(并且未成为)用户输入.pricefloat

要纠正,ignore()直到读完之后的下一个新行字符price.就像是:

cin.ignore(1024, '\n');
// or: cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Run Code Online (Sandbox Code Playgroud)

始终检查输入操作的状态以确定它们是否成功.这很容易实现:

if (cin >> price)
{
    // success.
}
Run Code Online (Sandbox Code Playgroud)

如果fishType可以包含空格,则使用operator>>(std::istream, std::string)不合适,因为它将停止在第一个空格处读取.std::getline()改为使用:

if (std::getline(cin, fishType))
{
}
Run Code Online (Sandbox Code Playgroud)

当用户输入输入时,将写入新的行字符stdin,即cin:

cod\n
1.9\n
salmon\n
2.7\n

在循环的第一次迭代:

cin >> fishType; // fishType == "cod" as operator>> std::string
                 // will read until first whitespace.
Run Code Online (Sandbox Code Playgroud)

并且cin现在包含:

\n
1.9\n
salmon\n
2.7\n

然后:

cin >> price; // This skips leading whitespace and price = 1.9
Run Code Online (Sandbox Code Playgroud)

并且cin现在包含:

\n
salmon\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.
Run Code Online (Sandbox Code Playgroud)