gpt4 book ai didi

c++ - 使用getline从文件中读取多行?

转载 作者:行者123 更新时间:2023-11-28 05:08:07 25 4
gpt4 key购买 nike

我正在尝试读取 names.txt 文件中的数据并输出每个人的全名和理想体重。使用循环从文件中读取每个人的姓名、英尺和英寸。文件内容如下:

汤姆阿托
6个
3个
伊顿赖特
5个
5个
卡里奥基
5个
11
奥马尔艾哈迈德
5个
9

我为此使用以下代码:

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();

当我运行这个时我得到输出:

Tom Atto 的理想体重
是185
理想体重
是-175

最佳答案

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

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

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

关于c++ - 使用getline从文件中读取多行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44171803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com