Reading a Text File into a 2d Array

I am trying to read this text file:

& @d|
dddd|
----|


into the char array Map[5][3].

My code just doesn't 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
47
48
char Map[6][4];
int row=0, col=0;


void Refresh();

int main(array<System::String ^> ^args)
{
	ifstream input( "C:\\TW.txt" );  //  The input file



	while( input ) 
	{
		input >> Map[ col ][ row ];

		if( input ) 
		{

			if( ++col == 5 ) 
			{       
				++row;                  
				col = 0;                
			}
			if(row>3)
			{
				break;
			}
		}                


	}

	Refresh();
	_getche();
}

void Refresh()
{
	system("CLS");
	for(int i=0; i<(row); i++)
	{
		for(int j=0; j<(col); j++)
		{
			cout << Map[j][i];
		}
	}
}


My code outputs this:

&@d|ddd|


I just can't find what is wrong...

Thank you so much,
Numeri
Last edited on
For printing it out in the same order as the text file put an extra cout << endl; on line 47 (after the inner for loop) so that a new line is created each time u loop through the columns of a row.

There's some bounds that are off by one like line 41 should be for(int i=0; i<=(row); i++);

The other problem u'll notice is that the whitespace on that first line in the text file is not being accounted for and this messes up the whole thing. There's different ways to deal with that, one uses the noskipws manipulator like input >> noskipws; //before while(input) . By doing it with this noskipws u'll have to discard those endline characters or they too will be stored into the array...

*If it's not guaranteed that each line in the text file is exactly 5 chars u'll have to determine when the end of the lines are.
Last edited on
Oh, that works perfect! Thanks so much. Where can I learn about more manipulators like the noskipws? I haven't really heard about them before.

Thanks!
Numeri
Thank you so much!
Topic archived. No new replies allowed.