Home > database >  Checking if input is a single character and meets validation in C
Checking if input is a single character and meets validation in C

Time:10-18

I'm new to the C language and have to write a program that asks the user to type the letter "t" in uppercase or lowercase and then press enter. The program should inform you if you entered the letter "t" or other data. The case of a user's input like "tre" should be treated as invalid. I've tried something like this:

#include <stdio.h>

int main(void) {
    char input;
    printf("Please type letter \"t\" in upper or lower case:\n");
    input = getchar();
    printf("%c", input);
    if (input != 't')
    {
        printf("\nWrong input");
        return 0;
    }
    else {
        printf("\nYou have entered: \"%c\"", input);
    }
}

The issue is that if the user's input is something like "tasd" or "tre" or anything that starts with the letter "t", only the first letter is read and the if statement is treated as true. I've tried to research the answer but I couldn't find anything useful.

CodePudding user response:

Check that the next character is an end of line '\n'

#include <stdio.h>

int main(void)
{
    char input;
    char nextchar;
    printf("Please type letter \"t\" in upper or lower case:\n");
    input = getchar();
    nextchar = getchar();
    printf("%c", input);
    if (input != 't' || nextchar!='\n')
    {
        printf("\nWrong input");
        return 0;
    }
    else
    {
        printf("\nYou have entered: \"%c\"", input);
    }
}

CodePudding user response:

You only read first char. You can solve that with a for loop till your char is equal to \n.

CodePudding user response:

Instead of reading a single char, read an entire string. put validations around the read string

  1. Size of input should be 1 char.
  2. The char should be 't'/'T'

CodePudding user response:

For starters the variable input should have the type int.

int input;

Instead of reading one character

input = getchar();

you could use for example

#include <ctype.h>
#include <stdio.h>

//...

int valid = ( input = getchar() ) != EOF && toupper( ( unsigned char )input ) == 'T';

if ( valid )
{
    int tmp;
    while ( ( tmp = getchar() ) != '\n' && isblank( ( unsigned char )tmp ) );
    valid = tmp == '\n';
}

if ( valid )
{
    printf( "\nYou have entered: \"%c\"\n", input );
}
else
{
    puts( "\nWrong input" );
}

That is the used can enter the character 't' and when several spaces. Such input should be considered as valid.

CodePudding user response:

The scanset %1[tT] will scan one character that is either a t or T.
The %n specifier will capture the number of characters processed by scanf to that point in the format string.
The scanset %*[^\n] will scan and discard everything up to a newline.
With these you can loop until the user enters a t or T.

#include <stdio.h>
#include <stdlib.h>

int main ( void) {
    char t[2] = "";
    int scanned = 0;
    int done = 0;

    do {
        printf ( "enter t or T\n");
        done = scanf ( " %1[tT]", t); // scan whitespace then t or T
        if ( EOF == done) {
            fprintf ( stderr, "EOF\n");
            return 1;
        }
        if ( done) { // scanned a t or T
            scanned = 0;
            scanf ( "%*[^\n]%n", &scanned); // scan and discard up to newline. count characters
            if ( scanned) { // there were some characters
                done = 0;
            }
        }
        scanf ( "%*[^\n]"); // scan and discard up to newline
    } while ( ! done);

    return 0;
}

CodePudding user response:

According to the information provided in your question, you do not want to validate only the first character of input, but rather an entire line of input.

In order to read an entire line of input as a string, I recommend that you use the function fgets. Afterwards, you can examine the string to determine whether the input is valid or not.

Here is an example:

#include <stdio.h>
#include <stdlib.h>

int main( void )
{
    char line[200];

    //prompt user for input
    printf( "Please type letter \"t\" in upper or lower case: " );

    //attempt to read one line of input
    if ( fgets( line, sizeof line, stdin ) == NULL )
    {
        fprintf( stderr, "Error reading input!\n" );
        exit( EXIT_FAILURE );
    }

    //verify that input string is valid
    if ( ( line[0] == 't' || line[0] == 'T' ) && line[1] == '\n' )
        printf( "Input is valid. You entered \"%c\".\n", line[0] );
    else
        printf( "Input is invalid!\n" );
}

This program has the following behavior:

Please type letter "t" in upper or lower case: tre
Input is invalid!
Please type letter "t" in upper or lower case: t
Input is valid. You entered "t".
Please type letter "t" in upper or lower case: T
Input is valid. You entered "T".
  • Related