Hi all i have a file i'm trying to read into a vector array.
I've checked a few other post which got me as far as i did.
I keep running into an error where it's not allowing me to insert my string using the put_back() function. I keep getting a char error. The file i'm importing contains numbers and i'm trying to read it in as a string type to avoid loosing leading zeros.
On line 38 you try to push_back(...) to a string. Since you did already the correct resize(...) you can actually write it like so: array2D[row][col] = x;
Thanks for the reply, when i try that assignment my array gets loaded with zero's?
A friend mentioned that it's taking only the last value from the file and i should read into x every loop iteration, rather than reading once before the loop. Still stuck there. Not sure where to put the read?
while (getline(infile, line)) {
istringstream streamA(line);
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
}
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
using std::vector;
usingnamespace 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;
}