C取消引用指针警告,甚至认为它们都是字符

标签 c pointers stdin fgets

我有一些代码通过 fgetsstdin 获取输入。

我需要检测用户什么时候没有输入,因为那会破坏我的其他代码。

这是我的代码:

#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]);
        ^

除了firstfgets的第一个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/

相关文章:

c - 通过中断保护读取值

使用 gcc 编译 C 程序

python - 如何在 Python 中将数据从不同的本地/远程进程流式传输到程序的 STDIN 中?

c++ - C或C++语言中的数组实际上是指针吗

c - 使用 C 覆盖数组中的字符

从 stdin 计算简单赋值运算符 "="

c - Number Pad [Enter] 不在 C 中?

c - 将字符串分配给某物

C语言——从函数中返回一个值作为函数参数

构建二叉搜索树时的编译错误