如何从fgets检测空字符串 [英] How to detect empty string from fgets
问题描述
我试图将来自stdin的fgets输入检测为空(当我按Enter而不输入任何内容时).这是我的程序:
I'm trying to detect the input of fgets from stdin as empty (when I press enter without entering in anything). Here is my program:
int main()
{
char input[1000];
printf("Enter :");
fgets(input, 1000, stdin);
input[strlen(input) - 1] = '\0';
if(input != '\0'){
printf("hi");
}
return 0;
}
我想执行某种条件,使其不打印任何内容,但显然这种方式是不正确的.我还尝试了NULL,该方法无效.
I want to do some sort of condition which makes it not print anything, but clearly this way isn't right. I also tried NULL, which did not work.
谢谢!
推荐答案
我认为这是最易读的(但性能不佳):
I think this is the most readable (but not performant):
if (strlen(input) != 0) {
printf("hi");
}
但是为了教学,这里是您的风格,但随后进行了修正:
But for the sake of teaching here is your style, but then fixed:
if (input[0] != '\0') {
printf("hi");
}
为什么input[0]
?因为input
像这样对数组的第一个元素进行操作,就像指针一样,因此必须首先取消引用它才能使比较有用.
Why input[0]
? Because input
acts like a pointer to the first element of the array if you compare it like that and you first have to dereference it to make the comparison useful.
这篇关于如何从fgets检测空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!