在 C++ 中从文本文件中读取数字数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14516915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read Numeric Data from a Text File in C++
提问by Usman Naseer
For example, if data in an external text file is like this:
例如,如果外部文本文件中的数据是这样的:
45.78 67.90 87
34.89 346 0.98
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.
如何读取此文本文件并将每个数字分配给 C++ 中的变量?使用 ifstream,我可以打开文本文件并将第一个数字分配给变量,但我不知道如何读取空格后的下一个数字。
#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;
}
回答by Spook
Repeat >> reads in loop.
重复 >> 循环读取。
#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;
}
Result:
结果:
45.779999 67.900002 87.000000 34.889999 346.000000 0.980000
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;
}
Edit:In response to your comments in main question.
编辑:回应您对主要问题的评论。
You have two options.
你有两个选择。
- You can run previous code in a loop (or two loops) and throw away a defined number of values - for example, if you need the value at point (97, 60), you have to skip 5996 (= 60 * 100 + 96) values and use the last one. This will work if you're interested onlyin specified value.
- You can load the data into an array - as Jerry Coffin sugested. He already gave you quite nice class, which will solve the problem. Alternatively, you can use simple array to store the data.
- 您可以在一个循环(或两个循环)中运行先前的代码并丢弃定义数量的值 - 例如,如果您需要 (97, 60) 点处的值,则必须跳过 5996 (= 60 * 100 + 96 ) 值并使用最后一个。如果您只对指定的值感兴趣,这将起作用。
- 您可以将数据加载到数组中 - 正如 Jerry Coffin 所建议的那样。他已经给你上了很好的课,这将解决问题。或者,您可以使用简单数组来存储数据。
Edit:How to skip values in file
编辑:如何跳过文件中的值
To choose the 1234th value, use the following code:
要选择第 1234 个值,请使用以下代码:
int skipped = 1233;
for (int i = 0; i < skipped; i++)
{
float tmp;
myfile >> tmp;
}
myfile >> value;
回答by Jerry Coffin
It can depend, especially on whether your file will have the same number of items on each row or not. If it will, then you probably want a 2D matrix class of some sort, usually something like this:
它可能取决于,尤其是您的文件在每行上是否具有相同数量的项目。如果可以,那么您可能需要某种 2D 矩阵类,通常是这样的:
class array2D {
std::vector<double> data;
size_t columns;
public:
array2D(size_t x, size_t y) : columns(x), data(x*y) {}
double &operator(size_t x, size_t y) {
return data[y*columns+x];
}
};
Note that as it's written, this assumes you know the size you'll need up-front. That can be avoided, but the code gets a little larger and more complex.
请注意,正如所写的那样,这假设您预先知道需要的大小。这可以避免,但代码会变得更大更复杂。
In any case, to read the numbers and maintain the original structure, you'd typically read a line at a time into a string, then use a stringstream to read numbers from the line. This lets you store the data from each line into a separate row in your array.
在任何情况下,为了读取数字并保持原始结构,您通常一次将一行读入一个字符串,然后使用 stringstream 从该行读取数字。这使您可以将每行中的数据存储到数组中的单独行中。
If you don't know the size ahead of time or (especially) if different rows might not all contain the same number of numbers:
如果您事先不知道大小,或者(特别是)如果不同的行可能不都包含相同数量的数字:
11 12 13
23 34 56 78
You might want to use a std::vector<std::vector<double> >
instead. This does impose some overhead, but if different rows may have different sizes, it's an easy way to do the job.
您可能想使用 astd::vector<std::vector<double> >
代替。这确实会带来一些开销,但如果不同的行可能具有不同的大小,这是完成这项工作的一种简单方法。
std::vector<std::vector<double> > numbers;
std::string temp;
while (std::getline(infile, temp)) {
std::istringstream buffer(temp);
std::vector<double> line((std::istream_iterator<double>(buffer)),
std::istream_iterator<double>());
numbers.push_back(line);
}
...or, with a modern (C++11) compiler, you can use brackets for line
's initialization:
...或者,使用现代 (C++11) 编译器,您可以使用方括号进行line
's 初始化:
std::vector<double> line{std::istream_iterator<double>(buffer),
std::istream_iterator<double>()};
回答by Some programmer dude
The input operator for number skips leading whitespace, so you can just read the number in a loop:
number 的输入运算符跳过前导空格,因此您可以在循环中读取数字:
while (myfile >> a)
{
// ...
}
回答by Mike22LFC
you could read and write to a seperately like others. But if you want to write into the same one, you could try with this:
你可以像其他人一样单独读写。但是如果你想写入同一个,你可以试试这个:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
double data[size of your data];
std::ifstream input("file.txt");
for (int i = 0; i < size of your data; i++) {
input >> data[i];
std::cout<< data[i]<<std::endl;
}
}