String to char array

Hi everyone,

I am to write a simple game that reads a labyrinth from a txt file and there are some issues concerning the conversion from the string to array of chars. The program does not copy the string into chars-it shows some strange symbols instead. The file is just a matrix 4 on 5 filled with "X" for the sake of simplicity.

So firstly I read the file and assign the string to a string array, and then I divided it using the c_str function, but sadly it doesn't work. I really don't know what to do and I appreciate any help I can get.

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
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>

using namespace std;

int main()
{
	string str,line;
	string tab[4];
	char labyrinth_line[5];
	char labyrinth[4][5];
	
	
	ifstream file ("labyrinth.txt");
	if (file.is_open())
	{
		int i=0;
		while (!file.eof())
		{
			getline (file,str);
			tab[i]=str;
			i++;
		}
	}
	
	for (int i = 0; i < 4; i++)
	{
		for (int j = 0; j< 5; j++)
		{
			line=tab[i];
			strcpy (labyrinth_line, line.c_str());
			labyrinth[i][j]=labyrinth_line[j];
		}
	}

	for (int i = 0; i < 4; i++)
	{
		for (int j = 0; j < 5; j++)
		{
			cout << labyrinth[i][j];
		}
		cout<<"\n";
	}
	system("pause");
	return 0;
}


So thanks in advance :)
To read a file line by line:
1
2
3
4
5
6
std::ifstream file( "labyrinth.txt" ) ;
std::string line ;
while( std::getline( file, line ) ) // as long as we succeed in reading a line
{
    // use information in the line that was read
}

Ok, so I did what you recommended:

1
2
3
4
5
6
int i=0;
while(getline( file, line ) )
{
	tab[i]=line;
	i++;
}


but I still the array doesn't resemble the file. I haven't mentioned it, but I have something like "Cannot find or open the PDB file" several times in the debug output.

*****
problem solved-the cause was the wrong encoding, so thank you ;)
Last edited on
Topic archived. No new replies allowed.