我想知道如何确保只输入字符。有任何想法吗?
printf("Enter Customer Name");
scanf("%s",cname);
答案 0 :(得分:2)
您可以读取字符串,然后使用isalpha()
或类似功能进行扫描。
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define STR(x) #x
#define SSTR(x) STR(x)
#define STR_FMT(x) "%" SSTR(x) "s"
#define CNAME_MAX_LEN 50
int inputName(char *cname)
{
size_t i;
do
{
printf("Enter Customer Name: ");
fflush(stdout);
if (1 != scanf(STR_FMT(CNAME_MAX_LEN), cname))
return 1;
for (i = 0; isalpha(cname[i]); ++i);
}
while (i == 0 || cname[i]);
return 0;
}
int main()
{
char cname[CNAME_MAX_LEN + 1];
if (inputName(cname))
{
perror("error reading in name!\n");
return 1;
}
printf("cname is '%s'\n", cname);
return 0;
}
答案 1 :(得分:1)
您可以使用strspn()
来测试字符串,如下所示:
#include <stdio.h>
#include <string.h>
int main(void){
char str[100] = {0};
int len;
scanf ("%99s", str);
len = strlen(str);
if (len != strspn(str, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"))
printf ("Your string contains non-alphabet characters.\n");
else
printf ("Your string is good.\n");
return 0;
}