Home > Back-end >  read single character not first character with scanf/sscanf. (not %c)
read single character not first character with scanf/sscanf. (not %c)

Time:12-16

I want to have a problem that itś able to distinguish when the user inputs a char or a string. For example:

Given the input "A", then letter="A"; Given the input "ABC", then discard;

I want to be able to distinguish when the two cases happen, so that I can discard when the user inputs a string versus a single letter.

By now, I have the following code written in C:

char letter;
sscanf("%c",&letter);
scanf("%c",&letter):

With the code above, what I get is:

Given the input "A", then letter="A"; Given the input "ABC", then letter="A;

How can i make this work?

CodePudding user response:

One solution is to read an entire line of input as a string using fgets, and then to check the length of the string:

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

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

    //prompt user for input
    printf( "Please enter input: " );

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

    //remove newline character, if it exists
    line[strcspn(line,"\n")] = '\0';

    //check number of characters in input
    switch ( strlen( line ) )
    {
        case 0:
            printf( "The line is empty!\n" );
            break;
        case 1:
            printf( "The line contains only a single character.\n" );
            break;
        default:
            printf( "The input contains several characters.\n" );
            break;
    }
}

This program has the following behavior:

Please enter input: 
The line is empty!
Please enter input: a
The line contains only a single character.
Please enter input: ab
The input contains several characters.

CodePudding user response:

#include <stdio.h>
#include <string.h>

int main(void)
{

    char letter[128];

    if (fgets(letter, 128, stdin) != NULL)
    {
        letter[strcspn(letter,"\n")] = '\0'; // remove newline character if present
        if (strlen(letter) > 1)
        {
            letter[0] = '\0'; // empty the string
            // memset(letter,0,sizeof(letter)); also empties the array
        }
    }
}

CodePudding user response:

You can get it to work if you use fgets instead of scanf. With char *fgets(char *str, int n, FILE *stream) you get the string from the stream stdin. And then you iterate over the string in order to get its size. If it is greater than one you set the value of the string to "".

Basically:

char string[128];
fgets(string, 128, stdin);
for(int len=0;string[len]!='\0';len  );
if(len>1)
string = "";
  • Related