Search code examples
cstringinputscanf

Why am I getting a type error when reading a string as input in C using scanf?


int main(){
  char repeat = 'y';
  float answer;
  char operation[6] = "1 + 4";
  do{
    printf("Enter your operation in the format <number> <operand> <number>:\n");
    do{
      scanf("%s", &operation);
      printf("%s %lu\n", operation, strlen(operation));
      if (strlen(operation) == 5){
      break;
    }
    printf("Operation not in format <number> <operand> <number>, please try again.\n");
    }while(0);
    if (repeat == 'a'){
      answer = calculate(operation, answer);
    } else {
      answer = calculate(operation, 0);
    }
    printf("The answer to your operation is: %g\n", answer);
    printf("Would you like to do another operation? [y/n]\n");
    scanf("%c", &repeat);
    do{
      printf("Would you like to do an operation on the previous answer? [y/n]\n");
      scanf("%c", &repeat);
    } while(repeat != 'a' && repeat != 'y');
  } while(repeat == 'y' || repeat == 'a');
  return 0;
}

I have some experience programming, mostly in python and a small amount in java, and I wanted to try learning C so I have been trying to make a simple calculator but I am running into trouble when trying to read a string. When compiling this I get a warning for the first scanf statement, saying: calculator/calculator.c:46:19: warning: format specifies type 'char ' but the argument has type 'char ()[6]' [-Wformat] scanf("%s", &operation);

As I understand it, the below three lines are effectively the same as what I am doing in my main function, but when these lines are run they work properly in both a different file and if put into my main function.

char str[100] = "1 + 2";
scanf("%s", str); 
printf("%s", str);

What am I missing?


Solution

  • As I understand it, the below three lines are effectively the same as what I am doing in my main function

    char str[100] = "1 + 2";
    scanf("%s", str); 
    printf("%s", str);
    

    Look again:

    scanf("%s", &operation);
    

    On this line you're passing the address of the array instead of the array itself. This address has type char(*)[6] i.e. a pointer to an array of char of size 6. This differs from the type that %s expects which is char *, hence the error.

    On a side note, even if you fix this you won't get the desired results. The %s format specifier does not read a full line of text but instead reads a series of non-whitespace characters. So if you were to type in 1 + 3, the stored string would be "1".

    You would instead need to use fgets to read a full line, also making sure that you strip the newline character from the end of the string that will be read.

    Then you have this:

    scanf("%c", &repeat);
    

    Which will read any character including whitespace. You want to include a space at the start of the format string to consume any whitespace left in the input buffer:

    scanf(" %c", &repeat);