在 C++ 中循环遍历 .txt 文件的行

looping through lines of a .txt file in C++

提问人:Cheekumz 提问时间:12/4/2018 更新时间:12/4/2018 访问量:1398

问:

完全 C++ 初学者,正如标题所说,我正在尝试逐行循环读取 .txt 文件,同时在移动到下一行之前对行的数据执行计算。

int main() {

ifstream in_file;
string name;
int kiloWatt{};
int amperage{};
int cores{3};
int voltage{480};
double powerFactor{0.8}; 
double efficiency{0.93};
double root{};

in_file.open("../test.txt");
if(!in_file){
    cerr <<"Problem opening file" << endl;
    return 1;
}
while (in_file >> name >> kiloWatt){
    root = sqrt(cores);
    amperage = (kiloWatt*1000)/(root*voltage*powerFactor*efficiency);

    cout << setw(10) << name
         << setw(10) << kiloWatt
         << setw(10) << amperage
         << setw(10) << root
         << endl;
}
in_file.close();
return 0;

}

这有效,但是它在第一行之后关闭了循环,因此只显示一行。有人给我指出为什么?非常感谢。

其引用的 txt 文件如下所示:

name1 23.5
name2 45.6
name3 234.8
C++ 解析 IOSTREAM IOManip

评论

1赞 12/4/2018
kiloWatt应该是双倍的。
0赞 Cheekumz 12/4/2018
好吧,现在我觉得自己很傻。我已经看了几个小时了。干杯伙计!

答:

4赞 scohe001 12/4/2018 #1

kiloWatt是一个 int,所以在第一行,它会读作 ,看到一个非整数字符并停止。下一个是 ,您将尝试读入 ,这将失败,因为它不是一个数字 - 破坏您的循环。23name".5""name2"kiloWatt

更改为替身以解决此问题。kiloWatt