2017-05-25 112 views
0

我想读取names.txt文件中的数据,并输出每个人的全名和理想体重。使用循环从文件中读取每个人的姓名,英尺和英寸。 读取文件:使用getline从文件读取多行?

Tom Atto 6 3 Eaton Wright 5 5 Cary Oki 5 11 Omar Ahmed 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(); 

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

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

+0

你的问题是什么? – arslan

+0

为什么我得到错误的输出 –

回答

0

你是遇到问题,因为行后

inFile >> extraInches; 

在循环的第一次迭代中执行,流中仍有一个换行符。下一次拨打getline只需返回一个空行。随后致电

inFile >> feet; 

失败,但您不检查呼叫是否成功。

我想提一些关于您的问题的东西。

  1. 混合未格式化的输入,用getline,和格式化的输入,使用operator>>是充满了问题。躲开它。

  2. 要诊断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"; 

} 
1

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

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

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