假设一个文件存储数据如下图,现在要把这里面的每个数据都读取出来存到数组里,
10 10
0 0 0 1 0 0 0 0 0 1
0 0 1 1 1 0 1 1 0 1
0 0 0 0 1 0 1 0 0 1
1 0 0 1 0 0 1 1 0 1
0 1 0 1 1 0 1 0 1 1
0 1 0 0 0 1 0 1 0 0
1 0 0 0 1 0 0 1 0 0
0 1 0 0 0 0 0 0 1 1
0 0 0 1 0 0 1 1 0 0
1 0 0 0 0 0 0 0 0 0
在读取下面的0101...时我的做法是按行读取
ifstream file("...");
while(getline(file,content))
{
content.erase(remove(content.begin(), content.end(),' '),content.end());
++i;
strcpy(a,content.c_str());
}
但是当读取第一行的时候(10 10) :
如果还是按照上述方法读取的话,就读取不到所需要的数据(10),大家有什么优雅的方法去解决这一类问题吗(比如100,1000...但都是空格隔开,读出来的格式要是int型的),越简洁越好
When reading such a small file, a better habit is to read it into the memory first and then analyze it. Since this file format is not complicated, parsing is actually very simple.
If you insist on analyzing while reading, then focus on my
parse into array
paragraph.EDIT:
The comments say to parse the first line alone, that's easy.
Modify
parse into array
slightly:Added that the above is enough.
There is no universal parsing method for this kind of purely parsed text. However, you can consider handling it from the following two aspects:
1. The file is stored in binary format, and a structure similar to the following is defined for reading.