【问题标题】:looping through lines of a .txt file in C++在 C++ 中循环遍历 .txt 文件的行
【发布时间】: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


【解决方案1】:

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

kiloWatt 更改为 double 以解决此问题。

【讨论】:

    猜你喜欢
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多