Char错误从文本文件读取字符串到矢量数组C ++

时间:2015-04-20 08:50:28

标签: c++ arrays multidimensional-array vector

大家好我有一个文件我正在尝试读入矢量数组。 我已经检查了一些其他帖子,这让我尽我所能。 我一直遇到一个错误,它不允许我使用put_back()函数插入我的字符串。我一直收到一个char错误。

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
using std::vector;
using namespace std;
string outPutFileName;
vector<vector<string> > array2D;
#define HEIGHT 32
#define WIDTH 9

int main() {
string x;
string line;
string filename;
ifstream infile;


infile.open("file.txt");


if (infile.fail()) {
    cerr << " The file you are trying to access cannot be found or opened";
    exit(1);
}

array2D.resize(HEIGHT);
for (int i = 0; i < HEIGHT; ++i) {
    array2D[i].resize(WIDTH);
}
    while (getline(infile, line)) {
        istringstream streamA(line);

        while (streamA >> x) {
            for (int row = 0; row < HEIGHT; row++) {
                for (int col= 0; col < WIDTH; col++) {
                    array2D[row][col].push_back(x);
                    col++;
                }
                row++;
            }
        }

    }

    for (int i = 0; i <HEIGHT; i++) {
        for (int j = 0; j <WIDTH; j++) {
            cout << array2D[i][j] << " ";
        }
        cout << endl;
    }



    return 0;
}

2 个答案:

答案 0 :(得分:0)

array2D[row][col]的类型为std::string,您试图在其上调用push_back而不是其中一个向量。你可能意味着:

array2D[row][col] = x;

答案 1 :(得分:0)

感谢您的帮助,我找到了解决方案。

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
using std::vector;
using namespace std;
string outPutFileName;
vector<vector<string> > array2D;
#define HEIGHT 32
#define WIDTH 9

int main() {
string x;
string line;
string filename;
ifstream infile;


infile.open("file.txt");

//error check
if (infile.fail()) {
    cerr << " The file you are trying to access cannot be found or opened";
    exit(1);
}
array2D.resize(HEIGHT);
for (int i = 0; i < HEIGHT; ++i) {
    array2D[i].resize(WIDTH);
}
int row;
while (getline(infile, line)) {
    istringstream streamA(line);

    int col = 0;
    while (streamA >> x) {
        array2D[row][col] = x;
        col++; // Note: This might go out of bounds
    }
    row++; // Note: This might go out of bounds
}

    for (int i = 0; i <HEIGHT; i++) {
        for (int j = 0; j <WIDTH; j++) {
            cout << array2D[i][j] << " ";
        }
        cout << endl;
    }

    return 0;
}