r/C_Programming • u/MainSeason4301 • Sep 25 '26
Question Confused about strings seemingly resetting after future inputs.
Hello! Sorry that this is such a basic question but I'm genuinely confused about this weird problem I had with scanf and strings. I've only just begun learning C and have been following a beginner's guide over on github.
Below I've written what my code was while I was having issues. The issue was that when the time came to print the values it would return the boolean value just fine, but the string would be blank. I added some extra prints in there to check if it was taking the input at all and it was! It was only after the boolean value was taken and stored that user_input began to return blank. I then tried googling for a very long time and couldn't find any solution (other than the odd tidbit about scanf not being great for strings), so in an act of desperation I tried changing char user_input[10] to static char user_input[10] and then suddenly it worked!
Somewhere along the line it must be overwriting or erasing the data stored in the array but I just don't understand where or why? Apologies again that this is such a basic question but I'd just really like to understand this a bit better, especially as no solution I could find suggested anything remotely like this.
#include <stdio.h>
#include <stdbool.h>
int main() {
char user_input[10];
bool tof;
printf("Enter a string: ");
scanf("%s", user_input);
printf("Enter a boolean value: ");
scanf("%d", &tof);
printf("String: %s\n", user_input);
printf("Boolean value: %d\n", tof);
return 0;
}
View all comments
Show parent comment
4
u/Muffindrake Sep 25 '26 edited Sep 25 '26
Using scanf/printf are a futile exercise. The functions are loaded with so much legacy baggage that you're forced to look at the manual every time, and you're better off writing a new function with a friendlier interface.
bool is guaranteed to contain only 0 or 1, and bool always converts to int when it's used in an expression due to default promotion rules (which can yield surprising results), same with short. Types are always extended to preserve magnitude and sign
That's for printf, anyway. Using scanf correctly is almost impossible. Even your comment shows this symptom - what the fuck is "which will likely be the same size as bool" doing in the language? That's a defect.
But here is the legacy baggage again. New code should only use _BitInt, as those are exempt from these footguns and require you to cast to a larger type explicitly.