问题描述
是否有一种简单的方法可以确保您通过 scanf 读取字符。如果它是一个整数,我会使用 do while 循环
do{
printf("enter a number");
fehler = scanf(" %d",&x);
getchar();
} while(fehler!=1);
但是如果输入是字符串,我不完全确定该怎么做。我知道字母表存储为 ASCII 值,但 while 语句中的 if 约束似乎不起作用(除非我做错了)
char * temp2;
temp2 = malloc(sizeof(string));
do{
printf("PLease enter a string: ");
scanf(" %s",temp2);
getchar();
} while(temp2 <= 'A' && temp2 <= 'z')
解决方法
您不能将字符串与单个字符进行比较。您必须遍历整个字符串,检查每个字符。
#include <ctype.h>
int is_alphabetic(char *str) {
for (int i = 0; str[i]; i++) {
if (!isalpha(str[i])) {
return 0;
}
}
return 1;
}
...
do{
printf("Please enter an alphabetic string: ");
scanf(" %s",temp2);
getchar();
} while(!is_alphabetic(temp2));
,
你看到 printf 和 scanf 独立工作。无论您存储的是字符还是数字,都以数字的形式存储。现在它取决于 printf 函数的要求。 例如:如果您在某个位置存储“a”,则存储数字 97。现在,如果你打印一个数字,它会打印 97,如果你需要一个字符,它会给出 a。
#include <stdio.h>
int main()
{
int i = 97;
printf("%d \n",i);
printf("%c",i);
return 0;
}
查看结果。进一步的 char、int、long int 只是数据类型,它们指定为变量的输入保留的位数。
执行这个程序你就会明白:
#include <stdio.h>
int main()
{
int i;
for (i=97; i <=200 ; i++)
{
printf("%d %c,\t",i,i);
};
return 0;}
这将在打印为数字时显示一个 nmber,然后将 SAME 数字读取为字符。 请注意,内存中没有标记来存储它是哪种类型的数据。它直接存储为数字。
,scanf
绝对是错误的工具。但是,如果您只想读取字母字符,则可以使用以下内容轻松完成:
char s[32];
if( 1 == scanf(" %31[a-zA-Z]",s) ){ ... }
%31[a-zA-Z]
转换说明符将只匹配文字字符 a
到 z
和 A
到 Z
,并且最多只消耗 31 个字符输入。您必须始终使用带有 %s
或 %[]
转换说明符的字段宽度修饰符以避免溢出。