![](/img/trans.png)
[英]How do I take input from a user that includes a string and integer separated by white space?
[英]How do I take one word as input from the user, and print “illegal input” if there's a number or a space?
char word[20];
printf("Enter a word: ");
gets(word);
for(int i=0;i<strlen(word);i++){
if((word[i]>=97 && word[i]<=122) || (word[i]>=65 && word[i]<=90)){
printf("Alphabet");
break;
}else{
printf("Illegal input");
break;
}
}
为什么这是错误的? 我只需要来自用户的一句话。 如果有任何空格或非字母字符,它必须打印非法输入。 我该如何纠正?
您的代码问题与字母字符检查无关:实际上,您实际上只是在检查字符串的第一个字符,因为您在if
和else
分支中都打破了循环。
我想您只是想在发现无效字符时中断详细说明:
#include <ctype.h>
#include <string.h>
char word[20];
printf("Enter a word: ");
fgets(word, 19, stdin);
word[strcspnn(word, "\n")] = 0;
for(int i=0;i<strlen(word);i++){
if((isalpha(word[i]))){
printf("Alphabet");
// break; // No break required here!
}else{
printf("Illegal input");
break;
}
}
请注意如何:
fgets
而不是gets
:后者已被弃用,因为它不安全。 另一方面, fgets
能够控制获取的字符数,没有超出word
数组大小的风险fgets
还存储了尾随换行符,我搜索它并用字符串终止符替换(如[此处]精彩显示)( https://stackoverflow.com/a/28462221/11336762 )ctype.h
标准函数isaplha()
来执行相同的操作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.