0

I have a variable where the user inputs one number. That variable is of type int because that's the return value of fgetc(stdin) and getchar(). In this case, I'm using fgetc(stdin). After the user inputs the number, I would like to convert it to an integer with strtol(), however, I get a warning about an incompatible integer to pointer conversion because of strtol()'s first argument being a const char *. Here is the code:

int option;
char *endptr;
int8_t choice;

printf("=========================================Login or Create Account=========================================\n\n");
while(1) {
    printf("Welcome to the Bank management program! Would you like to 1. Create Account or 2. Login?\n>>> ");
    fflush(stdout);
    option = fgetc(stdin);
    choice = strtol(option, &endptr, 10);

Does anyone know how to get around this?

Matthew Schell
  • 599
  • 1
  • 6
  • 19

2 Answers2

1

strtol is used to convert a "string" into long, not a single char. You just need choice = option - '0' to get the value. But you don't actually need to convert because you can directly switch on the char value

switch (option)
{
    case '1':
        // ...
        break;
    case '2':
        // ...
        break;
}

If you really want to call strtol then you must make a string

char[2] str;
str[0] = option;
str[1] = 0; // null terminator
choice = strtol(str, &endptr, 10);
phuclv
  • 37,963
  • 15
  • 156
  • 475
  • Oh ok. Thanks. I'll go ahead and do that. But let's say I did want to turn it into an `int`, would it be possible without getting any warnings? – Matthew Schell Jan 29 '21 at 02:52
  • the warning is there because it's wrong and your code won't work. But yes, see my edit – phuclv Jan 29 '21 at 03:13
0

since the variable 'option' is already an integer, there is no reason to call 'strtol' anymore.

or you can used gets to get a buffer from stdin, then transform the buffer into integer by strtol.

Paul Yang
  • 346
  • 2
  • 9