从C ++中的文本文件中读取数值数据 [英] Read Numeric Data from a Text File in C++
问题描述
例如,如果外部文本文件中的数据如下所示:
For example, if data in an external text file is like this:
45.78 67.90 87
34.89 346 0.98
如何读取此文本文件并将每个数字分配给c ++中的变量?
使用ifstream,我可以打开文本文件并将第一个数字赋给变量,但我不知道如何读取空格后的下一个数字。
How can I read this text file and assign each number to a variable in c++? Using ifstream, I am able to open the text file and assign first number to a variable, but I don't know how to read the next number after the spaces.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
float a;
ifstream myfile;
myfile.open("data.txt");
myfile >> a;
cout << a;
myfile.close();
system("pause");
return 0;
}
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int data[6], a, b, c, d, e, f;
ifstream myfile;
myfile.open("a.txt");
for(int i = 0; i << 6; i++)
myfile >> data[i];
myfile.close();
a = data[0];
b = data[1];
c = data[2];
d = data[3];
e = data[4];
f = data[5];
cout << a << "\t" << b << "\t" << c << "\t" << d << "\t" << e << "\t" << f << "\n";
system("pause");
return 0;
}
推荐答案
。
#include <iostream>
#include <fstream>
int main(int argc, char * argv[])
{
std::fstream myfile("D:\\data.txt", std::ios_base::in);
float a;
while (myfile >> a)
{
printf("%f ", a);
}
getchar();
return 0;
}
结果:
45.779999 67.900002 87.000000 34.889999 346.000000 0.980000
如果您确切地知道有一个文件,你可以链>>运算符:
If you know exactly, how many elements there are in a file, you can chain >> operator:
int main(int argc, char * argv[])
{
std::fstream myfile("D:\\data.txt", std::ios_base::in);
float a, b, c, d, e, f;
myfile >> a >> b >> c >> d >> e >> f;
printf("%f\t%f\t%f\t%f\t%f\t%f\n", a, b, c, d, e, f);
getchar();
return 0;
}
:回应您在主要问题中的意见。
In response to your comments in main question.
您有两个选项。
- 您可以在循环(或两个循环)中运行以前的代码,并丢弃定义数量的值 - 例如,在点(97,60)的值,您必须跳过5996(= 60 * 100 + 96)值并使用最后一个值。
- 您可以将数据加载到数组中 - 如Jerry Coffin sugested。他已经给你相当不错的课,这将解决问题。
编辑:如何跳过文件中的值
要选择第1234个值,请使用以下代码:
To choose the 1234th value, use the following code:
int skipped = 1233;
for (int i = 0; i < skipped; i++)
{
float tmp;
myfile >> tmp;
}
myfile >> value;
这篇关于从C ++中的文本文件中读取数值数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!