开发者社区> 问答> 正文

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) :

展开
收起
a123456678 2016-06-07 18:15:01 4123 0
1 条回答
写回答
取消 提交回答
  • 读这种并不大的文件,比较好的习惯是先统一读到内存中,再做解析。由于这个文件格式并不复杂,解析其实非常简单。
    
    #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++])
        ;
    补充称上面这样就行了。
    2019-07-17 19:30:39
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
使用C++11开发PHP7扩展 立即下载
GPON Class C++ SFP O;T Transce 立即下载
GPON Class C++ SFP OLT Transce 立即下载