How do I limit my user input

Luke

I've been creating a program requesting the user to input a char value, but if they enter more than one character it will move onto the next function and break the program. I've added in the second method which gets run when multiple inputs are entered.

Clifford

Your problem is not one of limiting the number of characters written to cInput; the format specifier %1s does that already. Your problem is one of leaving unprocessed characters in the input buffer. You need to remove all characters from the buffer if subsequent input will not handle them. For example if you leave a alphabetic character in then buffer but later read with %d, the function will return immediately (because there is implicitly a newline also buffered), but the character will remain buffered because it is not a decimal. This will continue indefinitely if you never clear the buffer.

For a single character, you can check the character is not a newline, and then repeatedly get characters until a newline is found, as follows:

scanf("%c", &cInput ) ;
while( cInout != '\n' && getchar() != '\n' ) { } // flush buffered line

If you want to be sure the user only enters a single character, then you could modify the above thus:

scanf("%c", &cInput ) ;   // Get a single character

if( cInput != '\n' &&     // If the input is not "empty",
    getchar() != '\n' )   // but the first character entered was not
                          // immediately followed by a newline...
{
    // Flush to the end of the entered line
    while( getchar() != '\n' ) { }

    // Invalidate the input to force retry
    cInput = 0 ;
}

At least one character will be buffered - a newline at least. A valid answer will have two characters one in cInput and a newline. The if(...) condition above reads the second character if there is one (using short-circuit evaluation of cInput), and checks that it is the end of the input (newline). If it is not, it reads all buffered characters then invalidates cInput (in case say "No-way\n" were entered for example, so that cinput contained 'N'.

For numeric input, you simply read characters until the newline is found:

scanf("%d", &nValue);
while( getchar() != '\n' ) { } // flush buffered line 

If trailing non-numeric characters should render the entire input invalid, you need to check that the following character is a newline.

int converted = scanf("%d", &nValue);
if( converted == 0 || getchar() != '\n' )
{
    valid_input = false ;
    while( getchar() != '\n' ) { } // flush buffered line 
}

Note that there are other possible solutions. This is my preferred solution.

When applied to your functions (with other simplifications):

int intAskUser(void)
{
    char cInput = 0 ;

    while( cInput != 'N' && cInput != 'Y' )
    {
        printf("Do you want to enter a value? Y or N\n");
        scanf("%c", &cInput ) ;
        if( cInput != '\n' && getchar() != '\n' )
        {
            while( getchar() != '\n' ) { } // flush buffered line
            cInput = 0 ;
        }
        else
        {
            cInput = toupper(cInput) ;
        }
    }

    // Return answer code 0 to 1
    return (cInput == 'N') ? 0 : 1 ;
}

int getValue(int nLower, int nUpper)
{
    assert( nLower < nUpper ) ;  // precondition check

    int nValue = 0 ; 
    bool valid_input = false ;

    while( !valid_input )
    {
        printf("Enter a value between %d and %d: ", nLower, nUpper ) ;
        int converted = scanf("%d", &nValue);
        if( converted == 0 || getchar() != '\n' )
        {
            valid_input = false ;
            while( getchar() != '\n' ) { } // flush buffered line 
        }

        valid_input = nValue >= nLower && 
                      nValue <= nUpper ;

        if( !valid_input )
        {
            printf( "Please try again. " );
        }
    } 

    printf("Value: %d", nValue);
    return nValue;
}

Note that toupper() requires ctype.h to be included, and the type bool requires stdbool.h.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How do i take user input and store it successfully in an ArrayList? Then how do i get my program to show me all the elements in the ArrayList?

How do i validate integer as user input?

How can I limit my selector to a specific element related to an input?

How do I convert user input into a list?

How do I prompt for user input in AutoHotkey?

How do I limit user input to specific integers, and keep track of exceptions, in Python 2.7?

How do I use recursion to loop my code (when user enters invalid input, it prompts them again)?

How do I style text input by a user?

How do I limit the amount of tasks allowed to input in my task list?

How do I get user input to use my validate method for a login console application?

How do I get user input validation into my java calculator program?

How do I calculate the total sum of my cart to my dictionary list based on user input menu?

Windows 10 How do I lock / limit another user's access to my folders?

How do I keep a user input? (php)

How do I show my switch function that my string variable equals user input

How do I limit the size of my syslog?

How do I make my nextLine() wait for the user's input?

How can I confirm the user limit of my google cloud/API?

How do I output answer of my user input knowledge base in Prolog

How do I limit user input to two possible strings?

How do I add a "catch all" term for my user input function in MatLab?

How do i repeat asking for input after my user pressed enter on my input prompt

How do I bring my user input to another method?

How do I limit the user from entering the wrong format for my time field

How do I match an user input to username in my txt file in Python?

How can I limit the expanding of my input?

How do I limit input attempts in python?

How can I limit the user input in quantity?

How do I correct my Sorter methods to allow for more user input?

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive