提问人:Cheekumz 提问时间:12/4/2018 更新时间:12/4/2018 访问量:1398
在 C++ 中循环遍历 .txt 文件的行
looping through lines of a .txt file in C++
问:
完全 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
答:
4赞
scohe001
12/4/2018
#1
kiloWatt
是一个 int,所以在第一行,它会读作 ,看到一个非整数字符并停止。下一个是 ,您将尝试读入 ,这将失败,因为它不是一个数字 - 破坏您的循环。23
name
".5"
"name2"
kiloWatt
更改为替身以解决此问题。kiloWatt
评论
kiloWatt
应该是双倍的。