I keep getting errors in my input in scanf_s, how do I fix it?

Asked 1 years ago, Updated 1 years ago, 439 views

      char name[256];
    printf("What's your name? ");
    scanf_s("%s", name,sizeof(name));

runs properly, but displays c4477,c6328 error So,

    char name[256];
    printf("What's your name? ");
    scanf_s("%s", name,(unsigned char)sizeof(name)); 

The error does not appear, but the characters appear strangely when running.

What should I do to make sure that I don't get errors and run them properly?

scanf

2023-04-21 22:23

1 Answers

In the question, the block below is a normal code. String input is normal.

char name[256];
printf("What's your name? ");
scanf_s("%s", name,sizeof(name));

The c4477 and c6328 errors are not caused by the scanf_s function, but by the error of specifying an argument type in another function that outputs or uses a saved name. Consider a function other than the scanf_s function.

char name[256];
printf("What's your name? ");
scanf_s("%s", name,(unsigned char)sizeof(name));

On the other hand, let me explain why the problem is occurring in the block above. The size of the name is 256. sizeof(name) returns 256, and we're doing a type conversion operation (unsigned char). Because the unsigned char type can only store values from 0 to 255, 256 is 0, which means that the value at the front is truncated. After all, it is the same as scanf_s("%s", name, 0);. Therefore, the name was not normally entered into the array, and eventually printed using the garbage value of the array, so we saw strange characters on the screen.


2023-04-21 22:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.