Archived

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

Turning a member of a string to an integer?

This topic is 6365 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

This is bothering me, How do I turn a member of a string to an integer, let''s say: char string1[9]; int number; scanf("%s", string1); some people might type in something like "hello", which is a string, but others might and will type in 5, or 6, or a number. So basically string1[0] is a number, but in string format. How do I like convert it into an integer format (store the value in number) without change its value? Like if someone type in a 6, and I do: printf("%d\n", number) It''ll like display 6, ya know? Thanx I want to work for Squaresoft ;)

Share this post


Link to post
Share on other sites
Convert it to an integer..

If you have:

char number[] = "32768"; // Number as text..

then you can say:

int n;
sscanf(number, "%d", &n);
printf("The number is %d\n", n);

Or, use the C-Runtime function atoi() (ascii to integer)

int n;
n = atoi(number);
printf("The number is %d\n", n);


Hope that helps..

// CHRIS

Share this post


Link to post
Share on other sites
AWWWW, I need to familiarize myself with the standard C library!!! That will be my goal for the next few weeks, hehe...

Thanks for the help man! I greatly appreciated

I want to work for Squaresoft ;)

Share this post


Link to post
Share on other sites
Let this be a testament to the dangers of self education:
I never knew about atoi(), I actually wrote my own function to do this..I felt pretty good at the time, now I feel sort of ridiculous ..you can all start laughing now..

"Like all good things, it starts with a monkey.."

Share this post


Link to post
Share on other sites
The ato* functions are unreliable. They return 0 if they can''t successfuly convert the given string to a number. So there''s no way of determining if the user entered "0" or an invalid number. Use sscanf instead.

Share this post


Link to post
Share on other sites