Archived

This topic is now archived and is closed to further replies.

using fgets() to read a line of txt to an int

This topic is 5518 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

i played around with this for a while, and found no solution, here''s what i got:
  
void BATTLE::MakeallMon()
{
	string tmpname;
	char templine[11];
	FILE *ReadMonlocs; //initalize readmonlocs

	ReadMonlocs = fopen("monlocs.txt", "r"); //open a stream

	
 	while(fgets(templine, 11, ReadMonlocs))
 	{
   		if((string)templine == "[location]")
 		{
 			system("cls");//debug

 			fgets(templine, 11, ReadMonlocs);
 			fgets(templine, 11, ReadMonlocs);
 			tmpname = templine;
 			cout << "tmpname: " << tmpname;

 			system("pause");//debug

 			MakeMon((int)fgets(templine, 11, ReadMonlocs), (int)fgets(templine, 11, ReadMonlocs), tmpname);
 		}
 	}
	fclose(ReadMonlocs);
}
void BATTLE::MakeMon(int tx, int ty, string tname)
{
	system("cls");
	cout << "x: " << tx << endl << "y :" << ty << endl << "name: " << tname << endl;
	system("pause");
}
  
when i call makeallmons() it says that x and y are some crazy ass numbers like 29832 or something, where as the text file has like 10. excuse the probabyl crappy grammar and stuff, its almost 5 am here... -Iron Eye
Cyrus Eye design

Share this post


Link to post
Share on other sites
When you call MakeMon you are casting the char returned by fgets as an int. This isn''t a valid conversion of a char string to int (at least not for the way you want) because "10" will not convert to 10.
Remember that the ASCII value of the character "1" is decimal 49 and "0" is 48 so if you just treat them as int you will get the wrong value.
Instead use the atoi(const char *string) function which will correctly convert for you.

Also make sure you understand the operation of the fgets function to ensure you are reading the strings you think you are.

Rhys Jones.

Share this post


Link to post
Share on other sites
When you call MakeMon you are casting the char returned by fgets as an int. This isn''t a valid conversion of a char string to int (at least not for the way you want) because "10" will not convert to 10.
Remember that the ASCII value of the character "1" is decimal 49 and "0" is 48 so if you just treat them as int you will get the wrong value.
Instead use the atoi(const char *string) function which will correctly convert for you.

Also make sure you understand the operation of the fgets function to ensure you are reading the strings you think you are.

Rhys Jones.

Share this post


Link to post
Share on other sites