fscan bad pointer

Feb 9, 2013 at 4:07am
What's wrong with this code?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
if (myPlayerFile)
		{
			int data = -1;
			string lol = "";

			fscanf(myPlayerFile, "%s", &lol); // s
			Player.setName(lol);

			fscanf(myPlayerFile, "%d", &data);
			Player.setCurMap(data);
			fscanf(myPlayerFile, "%d", &data);
			Player.setCurX(data);
			fscanf(myPlayerFile, "%d", &data);
			Player.setCurY(data);
			fscanf(myPlayerFile, "%d", &data);
			Player.Turn(data);

			//myTile[i].SetTileID(tile);
			
			fclose(myPlayerFile);
		}

for some reason my :

fscanf(myPlayerFile, "%s", &lol); // s

had no value (bad pointer)

how do i fix it?
Last edited on Feb 9, 2013 at 7:08am
Feb 9, 2013 at 7:15am
You should use a C-style string: char* lol;char lol[ 50 ];.

Also look at this: http://www.cplusplus.com/reference/cstdio/fscanf/
Last edited on Feb 9, 2013 at 7:21am
Feb 9, 2013 at 7:19am
Im using String for the character name in a class
that why im using string

plus here is the else part:

1
2
3
4
5
6
7
8
9
10
11
12
else

		{
			myPlayerFile = fopen(temp, "wt");
			
			fprintf(myPlayerFile, "%s ", Player.GetName().c_str());
			fprintf(myPlayerFile, "%d ", Player.GetCurMap());
			fprintf(myPlayerFile, "%d ", Player.GetCurX());
			fprintf(myPlayerFile, "%d ", Player.GetCurY());
			fprintf(myPlayerFile, "%d ", Player.GetCurDir());
			
		}


the fprint in here allow string to work

i dont see what i did wrong that give me bad pointer at all
Feb 9, 2013 at 7:23am
line 6 in your first post:

fscanf(myPlayerFile, "%s", &lol); should be fscanf(myPlayerFile, "%s", lol);
Feb 9, 2013 at 7:26am
I think fprint allows it here because you use the .c_str() part, which returns a C-string.
But what you can do is get the input in a C-style string, and then pass that string to Player.setName().
Feb 9, 2013 at 7:29am

Smac89 (180) Feb 8, 2013 at 11:23pm
line 6 in your first post:

fscanf(myPlayerFile, "%s", &lol); should be fscanf(myPlayerFile, "%s", lol);



When i do that i get access violation error

But what you can do is get the input in a C-style string, and then pass that string to Player.setName().


can you please show me an example? as in convert Char to string and such (if that is what you mean)
Feb 9, 2013 at 7:57am
1
2
3
char lol[ 50 ];
fscanf( myPlayerFile, "%s", lol );
Player.setName( lol );

lol is converted to a std::string (using the std::string constructor) when it is passed to setName().
Last edited on Feb 9, 2013 at 7:57am
Feb 9, 2013 at 8:04am
holy cow
it's worked

thank you very much :D

:3

i didnt know a char will be converted to a string upon the %s comment, but now i know, thank you very much :3
Feb 9, 2013 at 10:22am
you're welcome :)
Topic archived. No new replies allowed.