我有一些代码通过 fgets
从 stdin
获取输入。
我需要检测用户什么时候没有输入,因为那会破坏我的其他代码。
这是我的代码:
#include <stdio.h>
int main(void){
char input[100];
char first;
printf("Input something:\n>\n");
first = (char)(&fgets(input, 100, stdin)[0]);
if(first == "\n"){
// handle empty input here...
}
}
问题是它给了我一个警告:
main.c:6:10: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
first = (char)(&fgets(name1point, 100, stdin)[0]);
^
除了first
和fgets
的第一个char都是char类型。
如果我这样做
if(fgets(input, 100, stdin)[0] == "\n"){
然后它给了我一个警告:
main.c:7:12: warning: comparison between pointer and integer
if(first == "\n"){
^~
那么我需要取消引用它。
谁能帮帮我?我是初学者。
最佳答案
一些事情:
fgets() 返回一个 char *,所以 &fgets() 是一个 char**,所以 &fgets()[0] 是 一个 char*,所以(避免为 C 倾注 yacc 语法来计算 一元和后缀表达式的句法输入和输出 (虽然很有趣)),只需删除'&'即可。
在比较if(first == "\n")时,first是一个char,所以让它成为 if(first == '\n')
所以...
#include <stdio.h>
int main(void){
char input[100];
char first;
printf("Input something:\n>\n");
#if 0
first = (char)(&fgets(input, 100, stdin)[0]);
if(first == "\n"){
// handle empty input here...
}
#else
first = (char)(fgets(input, 100, stdin)[0]);
if(first == '\n'){
// handle empty input here...
}
#endif
}
关于C取消引用指针警告,甚至认为它们都是字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49367537/