scanf to read int but read in char?

This is a discussion on scanf to read int but read in char? within the C Programming forums, part of the General Programming Boards category; I am writing a program that: scanf is set to read in an integer value, when it reads char it ...

  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
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    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 */
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  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, 02:01 AM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 03: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, 06: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, 02:27 PM

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