读取单个字符作为输入后,如何确定它是哪种类型的字符?例如,如何确定字符是数字、字母还是点?
发布于 2022-03-20 21:30:31
您可以使用
isdigit,isalpha,ispunct,isspace的函数空白字符。您可以找到C标准库这里的所有字符分类函数的完整列表。
如果要将比较限制为"a value“(即不使用任何标点符号),则可以直接将字符的值与'.'进行比较。
#include <stdio.h>
#include <ctype.h>
int main( void )
{
int c;
printf( "Please enter a single character: " );
c = getchar();
if ( isdigit( c ) )
{
printf( "The input is a digit.\n" );
}
else if ( isalpha( c ) )
{
printf( "The input is an alphabetical letter.\n" );
}
else if ( c == '.' )
{
printf( "The input is a dot.\n" );
}
else if ( ispunct( c ) )
{
printf( "The input is a punctuation character.\n" );
}
else if ( isspace( c ) )
{
printf( "The input is a whitespace character.\n" );
}
else
{
printf( "The input is not a digit, letter, punctuation or whitespace character.\n" );
}
}此程序具有以下行为:
Please enter a single character: j
The input is an alphabetical letter.Please enter a single character: 7
The input is a digit.Please enter a single character: .
The input is a dot.Please enter a single character: ;
The input is a punctuation character.Please enter a single character:
The input is a whitespace character.https://stackoverflow.com/questions/71550375
复制相似问题