• Announcements

Archived

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

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

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];

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

{
if((string)templine == "[location]")
{
system("cls");//debug

tmpname = templine;
cout << "tmpname: " << tmpname;

system("pause");//debug

}
}
}
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 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 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 on other sites
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]

• Forum Statistics

• Total Topics
627718
• Total Posts
2978793

• 9
• 9
• 21
• 14
• 12