another sscanf problem

This is a discussion on another sscanf problem within the C Programming forums, part of the General Programming Boards category; i am reading a line from a file with fgets. then trying to parse that line with sscanf to place ...

  1. #1
    Registered User wazilian's Avatar
    Join Date
    Oct 2001
    Posts
    26

    another sscanf problem

    i am reading a line from a file with fgets. then trying to parse that line with sscanf to place in 2 vars. but that is not working as i expect. take the following line as a line read from the file(unix format):

    Code:
    test=40
    now assuming the file has been opened correctly, which it has, the following code:

    Code:
    char buffer[255];
    char name[255];
    int int_var;
    
    if (fgets(buffer, sizeof(buffer), fp) == NULL) {
         printf("line read failed\n");
         fclose(fp);
         return;
    } else {
         sscanf(buffer, "%s=%d", &name, &int_var);
         printf("%s\n", name);
         printf("%d\n", int_var);
    }
    prints out name to equal "test=40", which is the whole line that was read. and int_var is equal to nothing. i replaced the "=" with a space " " in both code and the file(test 40). and that was parsed fine. just doesn't work with the "=" sign between the string and integer. odd to me. perhaps not to the rest of you. any idea why the "=" doesn't work for me here? thanx.
    wazilian
    King of Wazil

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Try this
    Code:
    if ( sscanf(buffer, "%254[^=]=%d", name, &int_var) == 2 )
    {
       printf("%s\n", name);
       printf("%d\n", int_var);
    }
    Last edited by Dave_Sinkula; 06-01-2004 at 03:16 PM. Reason: Added maximum field width to %[ specifier.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Registered User wazilian's Avatar
    Join Date
    Oct 2001
    Posts
    26
    that got it. kewl beans. thanx man.
    wazilian
    King of Wazil

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. WS_POPUP, continuation of old problem
    By blurrymadness in forum Windows Programming
    Replies: 1
    Last Post: 04-20-2007, 07:54 PM
  2. problem with sscanf
    By nevrax in forum C Programming
    Replies: 19
    Last Post: 04-14-2007, 11:59 PM
  3. sscanf problem
    By LordShme in forum C Programming
    Replies: 5
    Last Post: 12-05-2006, 09:09 PM
  4. Weird problem with sscanf
    By g4j31a5 in forum C++ Programming
    Replies: 17
    Last Post: 10-04-2006, 10:16 PM
  5. Laptop Problem
    By Boomba in forum Tech Board
    Replies: 1
    Last Post: 03-07-2006, 06:24 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21