我正在尝试读取names.txt文件中的数据,并输出每个人的全名和理想体重。使用循环从文件中读取每个人的姓名以及脚和英寸。
该文件显示为:

Tom Atto63Eaton Wright55Cary Oki511Omar Ahmed59

我为此使用以下代码:

string name;
int feet, extraInches, idealWeight;
ifstream inFile;

inFile.open ("names.txt");

while (getline(inFile,name))
{
    inFile >> feet;
    inFile >> extraInches;

    idealWeight = 110 + ((feet - 5) * 12 + extraInches) * 5;

    cout << "The ideal weight for " << name << " is " << idealWeight << "\n";

}
inFile.close();


当我运行此即时消息获取输出时:

The ideal weight for Tom Atto is 185The ideal weight for is -175

最佳答案

读取两个extraInches值后,在while循环中添加此语句。

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


在您在'\n'循环中读取的第二个整数之后,它将忽略while。您可以参考:Use getline and >> when read file C++

09-30 15:47
查看更多