Thread: scanf to read int but read in char?

  1. #1
    Registered User
    Join Date
    Mar 2009
    Posts
    30

    scanf to read int but read in char?

    I am writing a program that:

    scanf is set to read in an integer value,
    when it reads char it goes into an infinite loop.
    The program should instead, print an error msg and break out of the loop.



    I tried to set everything in char and when it reads non digits it prints error message, but doesnt seem to work.
    any ideas?

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    Code:
    int x;
    int ch;
    if(scanf("%d", &x) != 1)
    {
       printf("Wrong format");
    }
    while((ch = getchar()) != '\n' && ch != EOF) ; /* get rid of the rest of the string */
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  3. #3
    Registered User
    Join Date
    Mar 2009
    Posts
    30
    sorry.. i don't quite get the code.
    ch is defined as int?
    what does it mean when its != 1.

  4. #4
    Registered User
    Join Date
    Mar 2009
    Posts
    30
    aha!
    i got it!
    thank you very much!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 01:01 AM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  3. Need help understanding info in a header file
    By hicpics in forum C Programming
    Replies: 8
    Last Post: 12-02-2005, 12:36 PM
  4. getting a headache
    By sreetvert83 in forum C++ Programming
    Replies: 41
    Last Post: 09-30-2005, 05:20 AM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM