使用scanf/sscanf读取单个字符,而不是第一个字符,(不是%c)

e0bqpujr  于 2022-12-17  发布在  其他
关注(0)|答案(3)|浏览(165)

我想有一个问题,它能够区分当用户输入字符或字符串。例如:
给定输入“A”,则字母=“A”;给定输入“ABC”,则丢弃;
我希望能够区分这两种情况发生的时间,以便可以在用户输入字符串和单个字母时丢弃。
到目前为止,我已经用C语言编写了以下代码:

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

使用上面的代码,我得到的是:
给定输入“A”,则字母=“A”;给定输入“ABC”,则字母=“A”;
我该怎么做呢?

vktxenjb

vktxenjb1#

一种解决方案是使用fgets将整行输入作为字符串读取,然后检查字符串的长度:

#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;
    }
}

此程序具有以下行为:
x一个一个一个一个x一个一个二个一个x一个一个三个一个

lymgl2op

lymgl2op2#

#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
        }
    }
}
n8ghc7c1

n8ghc7c13#

如果你用fgets代替scanf,你可以让它工作。用**char *fgets(char *str, int n, FILE *stream)**你可以从stdin流中得到字符串。然后你用strlen得到它的大小。如果它大于2(对于大小2,我们有字符本身和换行符),你把字符串的值设置为“\0”。
基本上:

#include "stdio.h"
#include "string.h"

int main(){
 char str[128];
 fgets(str, 128, stdin);
    
 if(strlen(str)>2)
    str[0]='\0';
   
return 0;

}

相关问题