Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take ints from user using fgets in C?

Tags:

c

pointers

fgets

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.

#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.
like image 505
johnwj Avatar asked Sep 21 '25 07:09

johnwj


1 Answers

First of all, a definition like

 char* height, width, depth;

make height a pointer to char and the rest two as 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 names directly, like

#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.

like image 180
Sourav Ghosh Avatar answered Sep 22 '25 20:09

Sourav Ghosh