文件读取 - C/C++如何从一个文件中把数据按需读取出来?
伊谢尔伦
伊谢尔伦 2017-04-17 11:34:38
0
4
662

假设一个文件存储数据如下图,现在要把这里面的每个数据都读取出来存到数组里,

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型的),越简洁越好
伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(4)
伊谢尔伦

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.

#include <iostream>
#include <fstream>
#include <sstream>

int main()
{
    const int size = 10*10+2;
    int arr[size];
    std::ifstream is("data.txt", std::ifstream::in);
    if (is)
    {
        // read into memory
        is.seekg (0, is.end);
        int length = is.tellg();
        is.seekg (0, is.beg);

        char *buffer = new char[length];
        is.read(buffer, length);
        is.close();

        // parse into array
        std::istringstream iss(buffer);
        int i = 0;
        while (iss >> arr[i++])
            ;
        delete [] buffer;

        // print or use it.
    }

    return 0;
} 

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:

// parse into array
std::istringstream iss(buffer);
// process first line
std::string headline;
getline(iss, headline);
sscanf(headline.c_str(), "%d %d", &a, &b);// a = 10, b = 10.
// process other part, into array.
int i = 0;
while (iss >> arr[i++])
    ;

Added that the above is enough.

巴扎黑
  while (getline(file, content)) {
    int a;
    istringstream is(content);
    while (is >> a) {
      cout << a << endl;
    }
  }
小葫芦
 int map[max] = {
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
}
巴扎黑

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.

tydefine HEADER {
    size_t w;
    size_t j;
    char   *a;
}Header;
  1. The files are stored in text format and processed using json, which is very convenient for encoding and reading.
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template