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

C++ 使用getline从文件中读取多行?,c++,while-loop,fstream,getline,C++,While Loop,Fstream,Getline,我试图读取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

我试图读取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();
字符串名;
内英尺,外英寸,理想重量;
河流充填;
infle.open(“names.txt”);
while(getline(填充,名称))
{
填充>>英尺;
填充>>额外英寸;
理想重量=110+((英尺-5)*12+额外英寸)*5;

你可能会遇到问题,因为排队后

inFile >> extraInches;
在循环的第一次迭代中执行,流中仍然有一个换行符。对
getline
的下一次调用只返回一个空行。后续调用

inFile >> feet;
失败,但您不检查呼叫是否成功

关于你的问题,我想提几件事

  • 混合使用
    getline
    的未格式化输入和使用
    operator>
    的格式化输入充满了问题。请避免

  • 要诊断IO相关问题,请始终在操作后检查流的状态

  • 在本例中,您可以使用
    getline
    读取文本行,然后使用
    istringstream
    从行中提取数字

    while (getline(inFile,name))
    {
       std::string line;
    
       // Read a line of text to extract the feet
       if ( !(inFile >> line ) )
       {
          // Problem
          break;
       }
       else
       {
          std::istringstream str(line);
          if ( !(str >> feet) )
          {
             // Problem
             break;
          }
       }
    
       // Read a line of text to extract the inches
       if ( !(inFile >> line ) )
       {
          // Problem
          break;
       }
       else
       {
          std::istringstream str(line);
          if ( !(str >> inches) )
          {
             // Problem
             break;
          }
       }
    
        idealWeight = 110 + ((feet - 5) * 12 + extraInches) * 5;
    
        cout << "The ideal weight for " << name << " is " << idealWeight << "\n";
    
    }
    
    while(getline(infle,name))
    {
    std::字符串行;
    //阅读一行文字以提取脚
    如果(!(填充>>行))
    {
    //问题
    打破
    }
    其他的
    {
    std::istringstream str(线路);
    如果(!(str>>英尺))
    {
    //问题
    打破
    }
    }
    //阅读一行文本以提取英寸
    如果(!(填充>>行))
    {
    //问题
    打破
    }
    其他的
    {
    std::istringstream str(线路);
    如果(!(str>>英寸))
    {
    //问题
    打破
    }
    }
    理想重量=110+((英尺-5)*12+额外英寸)*5;
    
    cout在读取两个额外英寸值后,将此语句添加到while循环中

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

    它会忽略在
    循环中读取的第二个整数之后的
    '\n'
    。您可以参考:

    您的问题是什么?为什么输出错误