在c ++中将文本文件读入2D verctor

时间:2016-04-21 17:22:13

标签: c++ file-io stdvector

我有一个带有一些文本行的文本文件

我想把文字放到2D矢量中,因为我 需要能够分别调用每个字符[x] [y]

这就是我所拥有的: 我在迷宫[i] [j]!=“\ 0”

上收到错误
int main() {
    // Variable declarations
    fstream file;
    int i=0;
    vector<vector<char> > maze(1,vector<char>(1));

ifstream myReadFile;
myReadFile.open("input.txt");

while (!myReadFile.eof()) {


        for (int j=0; maze[i][j] != "\0"; j++){
            myReadFile  >> maze[i][j];
        }
     i++;

}

    file.close();
    for (int i = 0; i < maze.size(); i++)
    {
        for (int j = 0; j < maze[i].size(); j++)
        {
            cout << maze[i][j];
        }
    }
        return 0;
}

我几乎找到了一个解决方案:

#include <fstream>
#include <stdio.h>
#include <string>
#include <sstream>

using namespace std;

template <typename T> //T could be of any data type
void printVector(T dvalue){//print the input data
 cout<<"List of the stored values "<<endl;
 for(int i=0; i<dvalue.size(); i++){
 for(int j=0; j<dvalue[i].size(); j++){
 cout<<dvalue[i][j]<<" ";
 }
 cout<<endl;
 }
}

int main(int argc, char* argv[]){
        cout<<"This example utilizes multi-dimensional vectors to read an input data file!"<<endl;
       vector< vector<string> > dvalue; //multidimensional vector declaration
        string line;
        fstream myfile; //define a myfile object of fstream class type
        myfile.open("input.txt"); //open the file passed through the main function

//read 1 line at a time.If the data points are seperated by comma it treats as a new line
        while(getline(myfile,line,'\n')){
                vector <string> v1;
                istringstream iss(line);//read the first line and store it in iss
                string value;
//this line breaks the row of data stored in iss into several columns and stores in the v1 vector
                while(iss>>value){
                        v1.push_back(value);
                }
                dvalue.push_back(v1);//store the input data row by row
        }
        printVector(dvalue);
return 0;
} 

但是这个不能处理多个空格,它输出为什么?

1 个答案:

答案 0 :(得分:0)

我可能会看到一些错误。

  1. 您将vector定义为1的大小,但尝试使用直接索引添加更多元素。它会导致异常。您应该使用push_back添加更多元素。

  2. 如果您想检查行尾,则字符为'\ r'和'\ n';

  3. 如果要比较字符,则使用'\ 0'而不是“\ 0”。
  4. 所以这是建议的代码:

    api.add_resource(ListStuff, '/list', endpoint='list')
    api.add_resource(ListStuff, '/api/list', endpoint='api-list')
    
    >>> print('URL for "list" is "{}"'.format(url_for('list'))
    >>> print('URL for "api-list" is "{}"'.format(url_for('api-list'))
    
    URL for "list" is "/list"
    URL for "api-list" is "/api/list"