Thread: How do you check for valid input?

  1. #1
    Registered User
    Join Date
    Jul 2003
    Posts
    49

    Question How do you check for valid input?

    Hi, I am trying to make a program that asks a user to enter a speed. The speed shoud be a positive int. How do I make it if a user enters say xyz, a message will say invalid input?

    eg
    int speed = 0;

    printf("Please enter a speed: "); --------user inputs xyz
    scanf("%d%", &speed);
    printf("Speed equals %d%", speed); ----the output would be 0

    is there a way to make it recognize xyz or whatever?

    Thanks heaps fo any info

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    You can't with scanf(). You should get input using fgets() and then use functions from ctype.h in your validation check. Look at functions like isdigit().
    If you understand what you're doing, you're not learning anything.

  3. #3
    Registered User
    Join Date
    Jul 2003
    Posts
    49
    Thanks itsme,

    I found a different solution before you post that seems to work

    int speed = -1000;

    printf("Please enter a speed: ");
    scanf("%d", &speed);

    if(speed == -1000)
    printf("Invalid input!\n");
    else
    if(speed < 0)
    printf("Invalid input!\n");

    i noticed speed remains the same when invalid input is used.

    Thanks again

  4. #4
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    The only problem with that is it leaves "xyz" in the input buffer, waiting for the next scanf() call. So if you loop back to the printf() when there's an invalid input you'll just get stuck in an infinite loop unless you go through the trouble of clearing the input buffer.

    I still think fgets() would be a much better choice. You could do something like:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <ctype.h>
    
    int main(void)
    {
      int speed;
      char buf[100];
    
      for(;;)
      {
        printf("Please enter a speed: ");
        fflush(stdout);  // Needed for non-newline'd printf()
    
        fgets(buf, sizeof(buf), stdin);
        speed = atoi(buf);
        if(!isdigit(*buf) || speed < 0)
          puts("Invalid input!");
        else
          break;
      }
    
      printf("You entered %d for the speed.\n", speed);
      return 0;
    }
    If you understand what you're doing, you're not learning anything.

  5. #5
    Registered User
    Join Date
    Jan 2005
    Posts
    184
    you can try this bit of code. which helps you in validating the input

    Code:
    #include<stdio.h>
    void flush(void);
    int main()
    {
            int speed;
            
            printf("Enter a integer value for speed\n?");
            while(!scanf("%d",&speed))   // on invalid conversion the scanf return 0 
            {
                printf("Inlvalid data\n");
                printf("Please enter a integer value\n");
                flush();
        }
        fflush(stdin);
            printf("you entered %d",speed);
            getchar();
       }      
       
    void flush()
    {   
        char c;
        while((c=getchar())!='\n');
        return;
    }
    s.s.harish

  6. #6
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    Code:
        fflush(stdin);
    Argh. Evil.
    If you understand what you're doing, you're not learning anything.

  7. #7
    Registered User
    Join Date
    Jan 2005
    Posts
    184
    ohh ya

    thats should't be used. any way no use of that in that prog.

    Code:
    #include<stdio.h>
    void flush(void);
    int main()
    {
            int speed;
            
            printf("Enter a integer value for speed\n?");
            while(!scanf("%d",&speed))
            {
                printf("Inlvalid data\n");
                printf("Please enter a integer value\n");
                flush();
        }
            printf("you entered %d",speed);
            getchar();
       }      
       
    void flush()
    {   
        char c;
        while((c=getchar())!='\n');
        return;
    }
    thax itsme86

    s.s.harish

  8. #8
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Code:
    void flush()
    {   
        char c;
        while((c=getchar())!='\n');
        return;
    }
    One more time?
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  9. #9
    Registered User
    Join Date
    Jan 2005
    Posts
    184
    very sorry

    getchar returns int right

    thats should be

    Code:
    int c;
    
    while((c=getchar())!='\n');
    return;

  10. #10
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    You may want to handle EOF, too.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  11. #11
    Registered User
    Join Date
    Jan 2005
    Posts
    184
    ok fine, need to check EOF as well
    Code:
    while((c=getchar())!='\n && ch!=EO);
    right

  12. #12
    Close,

    Current:
    Code:
    while((c=getchar())!='\n && ch!=EO);
    Correct:
    Code:
    while((c=getchar())!='\n' && c!=EOF);
    - Stack Overflow
    Last edited by Stack Overflow; 03-07-2005 at 04:45 PM.
    Segmentation Fault: I am an error in which a running program attempts to access memory not allocated to it and core dumps with a segmentation violation error. This is often caused by improper usage of pointers, attempts to access a non-existent or read-only physical memory address, re-use of memory if freed within the same scope, de-referencing a null pointer, or (in C) inadvertently using a non-pointer variable as a pointer.

  13. #13
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > right
    Still no - the idea is broken before it's begun, so there's really no point in trying to fix it.
    See, when you've fixed the flush, you've got the scanf to fix as well.

    > while(!scanf("%d",&speed))
    User signals EOF, the while loop exits (because scanf returns EOF) and your printf ends up printing some undefined value of speed.

    @itsme86
    > speed = atoi(buf);
    strtol() is better, since it also detects integer overflow as well as conversion errors.
    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.

  14. #14
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    Quote Originally Posted by Salem
    @itsme86
    > speed = atoi(buf);
    strtol() is better, since it also detects integer overflow as well as conversion errors.
    I can see that being true if speed is type long. But if, on a given architecture, ints and longs weren't the same size, couldn't it introduce its own problems?
    If you understand what you're doing, you're not learning anything.

  15. #15
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Worst case scenario it gets truncated. (If you're passing a long, and assigning it to an int.) And if that's the case, they've entered something too big anyway.

    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Input class project (again)
    By Elysia in forum C++ Programming
    Replies: 41
    Last Post: 02-13-2009, 10:52 AM
  2. can someone help me with these errors please code included
    By geekrockergal in forum C Programming
    Replies: 7
    Last Post: 02-10-2009, 02:20 PM
  3. allegro issues
    By mramazing in forum C++ Programming
    Replies: 1
    Last Post: 01-07-2009, 11:56 PM
  4. HELP!!!!emergency Problem~expert please help
    By unknowppl in forum C++ Programming
    Replies: 9
    Last Post: 08-21-2008, 06:41 PM
  5. check if user input matches a word
    By fakebloo in forum C++ Programming
    Replies: 1
    Last Post: 12-05-2004, 07:12 PM