【发布时间】:2019-05-05 00:27:44
【问题描述】:
总的 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
【问题讨论】:
-
kiloWatt应该是双精度的。 -
现在我觉得很傻。我已经看了好几个小时了。干杯队友!
标签: c++ parsing iostream iomanip