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

Started by
2 comments, last by Iron Eye 21 years, 5 months ago
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
---
ConPong _//_ Google _//_ Chaos Forge - quick and easy file hosting for developers

"Games usually keep me from making my own..."
-Me
---



find your elementat mutedfaith.com.
Advertisement
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.
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.
Yeah, I confirmed I was getting the right strings, thanks!
It worked!

EDIT: really sucky grammar, I'm tired.

-Iron Eye

Cyrus Eye design

[edited by - Iron Eye on November 8, 2002 3:24:03 PM]
---
ConPong _//_ Google _//_ Chaos Forge - quick and easy file hosting for developers

"Games usually keep me from making my own..."
-Me
---



find your elementat mutedfaith.com.

This topic is closed to new replies.

Advertisement