如何在 C 中使用 fgets 从用户那里获取整数?

joh*_*nwj 3 c pointers fgets

我是 C 的初学者。我正在尝试编写一个程序,该程序根据用户输入的 3 个整数来计算体积fgets(),我正在努力理解为什么我的代码不起作用。

#include <stdio.h>
#include <stdlib.h>

int volumn(int a, int b, int c);

int main(int argc, char* argv[]){
    char* height, width, depth;
    fgets(&height, 10, stdin);
    fgets(&width, 10, stdin);
    fgets(&depth, 10, stdin);

    printf("\nThe volumn is %d\n", volumn(atoi(&height), atoi(&width), atoi(&depth)));

    return 0;
}

int volumn(int a, int b, int c){
    return a * b * c;
}
Run Code Online (Sandbox Code Playgroud)

编辑:当我运行上面的代码时,我收到以下错误/警告:

goodbyeworld.c:8:11: warning: incompatible pointer types passing 'char **' to
      parameter of type 'char *'; remove & [-Wincompatible-pointer-types]
    fgets(&height, 10, stdin);
          ^~~~~~~
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/usr/include/stdio.h:238:30: note: 
      passing argument to parameter here
char    *fgets(char * __restrict, int, FILE *);
                                ^
goodbyeworld.c:12:48: warning: incompatible pointer types passing 'char **' to
      parameter of type 'const char *'; remove & [-Wincompatible-pointer-types]
    printf("\nThe volumn is %d\n", volumn(atoi(&height), atoi(&width), a...
                                               ^~~~~~~
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/usr/include/stdlib.h:132:23: note: 
      passing argument to parameter here
int      atoi(const char *);
                          ^
2 warnings generated.
Run Code Online (Sandbox Code Playgroud)

Sou*_*osh 5

首先,定义如下

 char* height, width, depth;
Run Code Online (Sandbox Code Playgroud)

height指针指向char其余两个作为chars。

其次(这里不太相关,但总的来说很重要),您没有为要使用的指针分配内存(如果有的话)。

如果您有一个固定的输入长度决定为10,您可以简单地将所有三个变量作为数组并直接使用名称,例如

#define VAL 10
char height[VAL] = {0};
char width[VAL] = {0};
char depth[VAL] = {0};
Run Code Online (Sandbox Code Playgroud)

进而

fgets(height, 10, stdin);
Run Code Online (Sandbox Code Playgroud)

最后,考虑使用strtol()overatoi()来更好地处理错误。