Thread: Getting an int value from stdin

  1. #1
    Registered User
    Join Date
    Sep 2003
    Posts
    69

    Getting an int value from stdin

    Hello,

    In the program I'm working on, I need to read in lines from stdin. Lines like this:

    Name 1 Name2 3

    What I want to do is tokenize the line. However, when I do this, it makes each token a char*, right? How do I make the 1 and 3 in the line into an int? Here is what I'm trying now, but I don't think it's right:

    Code:
    while( fgets(buf,BUFSIZ,stdin) ) {
           team1 = strtok(buf," ");
           score1 = (int)strtok(NULL," ");
           team2 = strtok(NULL," ");
           score2 = (int)strtok(NULL,"\n");
    Does the casting for score1 and score2 actually change the char* into an int? Thanks for the help.

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >but I don't think it's right
    It's not. Type coercion doesn't change the underlying representation, it just tricks the compiler into accepting something it wouldn't otherwise. To actually change a string to an int, you need to use either atoi or strtol with an int cast:
    Code:
    while( fgets(buf,BUFSIZ,stdin) ) {
           team1 = strtok(buf," ");
           score1 = atoi(strtok(NULL," "));
           team2 = strtok(NULL," ");
           score2 = atoi(strtok(NULL,"\n"));
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    Sep 2003
    Posts
    69
    Ah yes, atoi. I completely forgot about that function. Thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 05-13-2007, 08:55 AM
  2. Working with random like dice
    By SebastionV3 in forum C++ Programming
    Replies: 10
    Last Post: 05-26-2006, 09:16 PM
  3. Half-life SDK, where are the constants?
    By bennyandthejets in forum Game Programming
    Replies: 29
    Last Post: 08-25-2003, 11:58 AM
  4. Quack! It doesn't work! >.<
    By *Michelle* in forum C++ Programming
    Replies: 8
    Last Post: 03-02-2003, 12:26 AM
  5. easy if you know how to use functions...
    By Unregistered in forum C Programming
    Replies: 7
    Last Post: 01-31-2002, 07:34 AM