从文本文件中提取变量(C ++)

时间:2011-11-22 17:00:33

标签: c++

我需要从文本文件中将四个变量输入到C ++程序(Win32)中。每个变量都在各自的行上。

example.txt中:

2.651127
-7.802776
5.530998
-17.239931

这四个变量在我的程序中都是浮点数。 C ++中将每行传递给自己的变量的语法是什么?只有四个数字,每个都在各自的行上。

2 个答案:

答案 0 :(得分:4)

#include <fstream>
std::ifstream file("test.txt");
double a, b, c, d;
if(!(file >> a >> b >> c >> d)){
// error extracting the values!
}

答案 1 :(得分:0)

double d[4];
for (int i = 0; i < 4; i++)
  cin >> d[i];