Thread: sscanf question

  1. #1
    Registered User
    Join Date
    Oct 2003
    Posts
    5

    sscanf question

    Since a string is not a stream how do I get sscanf to traverse the string rather than keep reading the first thing? I want to use the following while loop but because of this problem it goes infinite

    Code:
    while((sscanf(myString, "%s", anotherString)) != EOF){
    .
    .
    .
    }
    Thanks

  2. #2
    Registered User
    Join Date
    Dec 2002
    Posts
    27
    sscanf never returns eof, it returns the count of
    variables it managed to scan in.
    Try
    Code:
    while (sscanf (......) != 0)
    {
    .
    .
    .
    .
    }
    "Can i really learn this? If i cant, why bother?"

  3. #3
    Registered User
    Join Date
    Oct 2003
    Posts
    5
    Thats not the problem.

    It doesnt traverse the string because it is not a stream. Everytime sscanf is executed, it reads the same thing each time.

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Something like
    Code:
    int pos = 0;
    char *p = myString;
    while ( sscanf( p, "%s%n", anotherString, &pos ) == 1 ) {
        // do stuff
        p += pos;   // advance p
    }
    %n tells you how many chars sscanf() processed
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  5. #5
    Registered User
    Join Date
    Oct 2003
    Posts
    5
    Ok i see why that works but why do I check if it equals 1?

  6. #6
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > Ok i see why that works but why do I check if it equals 1?
    Because I've read the sscanf() manual page, and you haven't...
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. another do while question
    By kbpsu in forum C++ Programming
    Replies: 3
    Last Post: 03-23-2009, 12:14 PM
  2. sscanf() question
    By NuNn in forum C Programming
    Replies: 7
    Last Post: 02-28-2009, 02:57 PM
  3. Problem using sscanf fgets and overflow checking
    By jou00jou in forum C Programming
    Replies: 5
    Last Post: 02-18-2008, 06:42 AM
  4. Dumb Question: What is sscanf?
    By KingZoolerius66 in forum C Programming
    Replies: 3
    Last Post: 10-04-2003, 08:19 PM
  5. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 09:47 PM