首页 > C/C++如何从一个文件中把数据按需读取出来?

C/C++如何从一个文件中把数据按需读取出来?

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

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

读这种并不大的文件,比较好的习惯是先统一读到内存中,再做解析。由于这个文件格式并不复杂,解析其实非常简单。

#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;
} 

如果你坚持边读边解析,那就重点看我parse into array那一段。

EDIT:
评论说要单独解析第一行,那很容易。
parse into array 稍作修改:

// 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++])
    ;

补充称上面这样就行了。


  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
}

这种纯解析的文本并没有通用的解析方法.但是可以考虑从以下两个方面来处理:
1. 文件存储为二进制格式,定义一个类似于如下的结构体进行进行读入。

tydefine HEADER {
    size_t w;
    size_t j;
    char   *a;
}Header;
  1. 文件存储为文本格式,采用json处理,无论是编码还是给人阅读都很方便。
【热门文章】
【热门文章】