Home > Mobile >  Errors about scanf and printf expected types
Errors about scanf and printf expected types

Time:05-07

My issue is coming from the %c name input, I am getting an error that it is expecting type char * but has type char * [15] for the scanf function. I am also getting an error in the printf where the %c expects int but has type char *. I am still quite new at this so if it could be explained as simply as possible that would be amazing.

#include <stdio.h>

struct Student {
    int StudentID;
    char Name[15];
    float Mark1;
    float Mark2;
    float Mark3;
} a;

int main() {
    float ave;
    printf("Please input Student's ID \n");
    scanf("%d", &a.StudentID);
    printf("Please input Student's name. \n");
    scanf(" %c", &a.Name);
    printf("Input Mark 1. \n");
    scanf("%f", &a.Mark1);
    printf("Input Mark 2. \n");
    scanf("%f", &a.Mark2);
    printf("Input Mark 3. \n");
    scanf("%f", &a.Mark3);
    ave = (a.Mark1   a.Mark2   a.Mark3) / 3;

    printf("Student Detail\nStudent ID: %d\nName: %c\nMark 1: %.2f\n Mark 2: %.2f\n Mark 3: %.2f\nAverage: %.2f\n",
           a.StudentID, a.Name, a.Mark1, a.Mark2, a.Mark3, ave);

    return 0;
}

CodePudding user response:

Your problem is related to the difference between an array of chars and a single char.

The %c format only reads in one character at a time.

If you wish to read a string of characters use %s and it will read until a null terminator. (Please make sure you don't try to read a name more than 14 characters long into your 15 character buffer)

In more depth, your char Name[15] is actually a pointer to a series of chars in memory. You are accidentally trying to change to pointer itself, instead of the chars that it points to. This is why the compiler expects a char * .

Instead if you truly meant to only read one char you could use

scanf(" %c", &a.Name[0]);

to place the character in the first block of the Name array.

If this is too complicated don't worry, it will all come eventually :)

For now I think %s will suffice.

** EDIT ** Also don't forget to use %s in the final printf as well

CodePudding user response:

In your scanf() call, %c tells scanf() to accept a single character. But your argument is a character array. C is a low-level language; it's not smart enough to realize you wanted a string (char array) as input. You have to tell it by using %s instead of %c.

  • Related