Thread: Simple question with scanf()

  1. #1
    Registered User
    Join Date
    Jul 2002
    Posts
    31

    Simple question with scanf()

    Let's say that I want scanf to process the following text

    balance = 100

    How do I skip over the word balance and the equal sign and capture only 100 and place it into an integer variable x?

    Thanks.

    Pier.

  2. #2
    and the Hat of Clumsiness GanglyLamb's Avatar
    Join Date
    Oct 2002
    Location
    between photons and phonons
    Posts
    1,110
    i should read the whole thing with fgets and then convert the string with sscanf (+check for succesfull conversion)

  3. #3
    Registered User Cela's Avatar
    Join Date
    Jan 2003
    Posts
    362
    >>Let's say that I want scanf to process the following text
    You'll have fewer headaches if you don't consider using scanf, ever. Reading the whole line with fgets and then breaking it up with sscanf is much nicer. :-)
    Code:
    #include <stdio.h>
    
    int main(void)
    {
      int num;
      char string[100];
    
      /* Assume :string:ws:char:ws:number: */
      if (fgets(string, 100, stdin) == 0)
      {
        return 1;
      }
      else if (sscanf(string, "%*s %*c %d", &num) == 1)
      {
        printf("Num -- %d\n", num);
      }
    
      return 0;
    }
    But if you really have to do it the ugly way, it's not much different.
    Code:
    #include <stdio.h>
    
    int main(void)
    {
      int num;
    
      /* Assume :string:ws:char:ws:number: */
      if (scanf("%*s %*c %d", &num) == 1)
      {
        printf("Num -- %d\n", num);
      }
    
      return 0;
    }
    *Cela*

  4. #4
    Registered User
    Join Date
    Jul 2002
    Posts
    31
    Thanks a lot guys

    Pier.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Simple question regarding variables
    By Flakster in forum C++ Programming
    Replies: 10
    Last Post: 05-18-2005, 08:10 PM
  2. Simple class question
    By 99atlantic in forum C++ Programming
    Replies: 6
    Last Post: 04-20-2005, 11:41 PM
  3. Simple question about pausing program
    By Noid in forum C Programming
    Replies: 14
    Last Post: 04-02-2005, 09:46 AM
  4. simple question.
    By InvariantLoop in forum Windows Programming
    Replies: 4
    Last Post: 01-31-2005, 12:15 PM
  5. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM