2d char array from file
May 5, 2011 at 6:52pm UTC
What I'm trying to do:
I'd like to fill a 2d char array with words read in from an ifstream.
I'd like to fill the array until the loop reads a '\n' and then jump a dimension in the array.
ex:
array[0][0] = A
array[1][0] = P
array[2][0] = P
array[3][0] = L
array[4][0] = E
array[0][1] = I
array[1][2] = D
array[2][3] = U
array[3][4] = M
array[4][5] = B
And now i'm confused =(
Here's what I though would work:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
#include <iostream>
#include <fstream>
using namespace std;
int main() {
char array[20][4];
char next;
int acount = 0, bcount = 0;
ifstream file;
file.open("test.txt" );
while (! file.eof()) {
file.get(next);
if (next != '\n' ) {
while (next != '\n' ) {
array[acount][bcount] = next;
file.get(next);
acount++;
}
}
else if (next == '\n' ) {
acount = 0;
bcount++;
array[acount][bcount] = next;
}
}
for (int i = 0; i < 21; i++) {
for (int j = 0; j < 5; j++) {
cout << array[i][j];
}
}
system("PAUSE" );
return 0;
}
Any help or tips much appreciated!
May 5, 2011 at 7:10pm UTC
Try this:
1 2 3 4 5 6
char array[20][4];
ifstream file("file.txt" );
for (int y = 0; y<20; y++){
for (int x = 0; x<4; x++){
file >> array[y][x];}}
EDIT: Nevermind.
Last edited on May 5, 2011 at 7:13pm UTC
Topic archived. No new replies allowed.