Thread: How to continue if no user input

  1. #1
    Registered User
    Join Date
    Oct 2011
    Posts
    24

    How to continue if no user input

    If I have a scanf like this:

    Code:
    scanf(" %c %lf", &charvar, &doublevar);
    How do I get the program to continue if the user only inputs the one char and no double character? For example if user hits 'R' and then return the program does not execute the next line of code. How do I get it to do that?

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Use fgets to read a line of input and sscanf to parse that line. Then read the documentation on sscanf (scanf(3): input format conversion - Linux man page), especially the part about "return value". It tells you that scanf returns the number of successfully converted items, so if it returns 1 instead of 2, you didn't get a valid float.

  3. #3
    Registered User
    Join Date
    Oct 2011
    Posts
    24
    I read the page you linked, but I am still not sure how to alter my code. I am a beginner...

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Hope is the first step on the road to disappointment.

  5. #5
    Registered User
    Join Date
    Oct 2011
    Posts
    24
    Sorry I still don't know what to do...

    doublevar is a double not a char:

    Code:
    scanf(" %c %lf", &charvar, &doublevar);

  6. #6
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Reading a line of input is done with fgets, as quzah's link shows. You can't use scanf like that for it, because it will swallow the return you type and wait for the next character. Using sscanf solves this because once it reaches the end of the string, it will not expect more input. But to use sscanf you must first put a line of text into a memory buffer, which fgets can do.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. End of user input must be 999
    By naspek in forum C Programming
    Replies: 23
    Last Post: 07-22-2009, 11:04 PM
  2. using user input as a var.
    By nubi in forum C++ Programming
    Replies: 13
    Last Post: 05-06-2003, 12:27 PM
  3. user input
    By hen in forum C Programming
    Replies: 1
    Last Post: 08-02-2002, 11:37 AM
  4. user input
    By hen in forum C Programming
    Replies: 4
    Last Post: 06-29-2002, 04:10 PM
  5. function to prompt user to continue entering data or not
    By Unregistered in forum C++ Programming
    Replies: 2
    Last Post: 05-05-2002, 06:38 PM

Tags for this Thread