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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32573382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 12:07:35  来源:igfitidea点击:

How to take ints from user using fgets in C?

cpointersfgets

提问by johnwj

I'm a beginner at C. I'm trying to write a program that computes the volume based on user's input of 3 integers using fgets(), and I'm struggling to understand why my code is not working.

我是 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;
}

EDIT: I'm getting the following errors/warnings when I run the code above:

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

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.

回答by Sourav Ghosh

First of all, a definition like

首先,定义如下

 char* height, width, depth;

make heighta pointer to charand the rest two as chars.

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

Secondly (not much relevant here, but in general, important), You did not allocate memory to the pointers you want to use (if at all).

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

If you have a fixed input length decided as 10, you can simply make all the three variables as array ans use the namesdirectly, like

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

#define VAL 10
char height[VAL] = {0};
char width[VAL] = {0};
char depth[VAL] = {0};

and then

进而

fgets(height, 10, stdin);

finally, consider using strtol()over atoi()for better error handling.

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

回答by Coffee'd Up Hacker

You shouldn't. Using atoito convert input to integers when you can get the input asintegers is pointless. What you are looking for is scanf.

你不应该。atoi当您可以将输入作为整数获取时,使用将输入转换整数是毫无意义的。您正在寻找的是scanf.

Your code would look like this...

你的代码看起来像这样......

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

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

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

    scanf ("%10d", &height);
    scanf ("%10d", &width);
    scanf ("%10d", &depth);

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

    return 0;
}

int
volumn (int a, int b, int c)
{
    return a * b * c;
} 

回答by user3629249

in C, the name of an array degrades to a pointer to the first address of the array,

在 C 中,数组的名称降级为指向数组首地址的指针,

However, the dimensions are already (only) pointers that point to nothing.

但是,维度已经(仅)是指向任何内容的指针。

The code needs to actually have them point to allocated memory.

代码需要实际让它们指向分配的内存。

Typically that would be accomplished via code similar to:

通常,这将通过类似于以下的代码来完成:

if( NULL == (height = malloc( 20 ) ) ) { // handle error and exit }

I use 20 rather than 10 because a int can be 13 characters plus sign plus newline plus NUL byte and 20 leaves a bit of extra room.

我使用 20 而不是 10,因为 int 可以是 13 个字符加符号加换行符加 NUL 字节,而 20 会留下一些额外的空间。

The first parameter to fgets() is a pointer to the input buffer and 'height', etc are defined as pointers so do not need another '&'

fgets() 的第一个参数是指向输入缓冲区的指针,'height' 等被定义为指针,因此不需要另一个 '&'

However, using malloc() also adds the requirement to pass each of the three pointers to free() before exiting the program.

但是,使用 malloc() 还增加了在退出程序之前将三个指针中的每一个都传递给 free() 的要求。

remembering that a int (on a 32 bit system) can handle +/-2gig I.E. 10 digits+sign+newline+NUL is a (depending on the OS) 13 or 14 characters.

记住 int (在 32 位系统上)可以处理 +/-2gig IE 10 位数字+符号+换行符+NUL 是(取决于操作系统)13 或 14 个字符。

Suggest, use:

建议,使用:

int main( void )
{
    int height;
    int width;
    int depth;

    if( 1 != (scanf( "%d", &height ) ) ) 
    { // then scanf failed
        perror( "scanf for height failed: );
        exit( EXIT_FAILURE );
    }

    // implied else, scanf successful

    similar statements for the other two inputs

    printf ("\nThe volumn is %d\n", volumn (height, width, depth));
    return 0;
} // end function: main

回答by metarose

Simple solution of your problem.

您的问题的简单解决方案。

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

int volumn(int a, int b, int c){
    return a*b*c;
}

int main(){

    char height[10];
    char width[10];
    char depth[10];

    printf("Please enter size of object:\n");
    fgets(height, 10, stdin);
    fgets(width, 10, stdin);
    fgets(depth, 10, stdin);

    int valheight = atoi(height);
    int valwidth = atoi(width);
    int valdepth = atoi(depth);

    printf("\nThe volumn is %i\n", volumn(valheight, valwidth, valdepth));

    return 0;
}