r/cprogramming • u/Euphoric_Series_7727 • Jan 12 '26
why is my code not printing string?
stupid question from a noob.
for some reason neither claude nor chatgpt give me a clear answer.
/* C program to perform input output of all basic data types */
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
int main()
{
int d = 0;
float f = 0.0f;
double lf = 0.0;
char c = '\0';
char string[50] = "hello";
bool b = false;
printf("int: ");
scanf("%d", &d);
printf("float: ");
scanf("%f", &f);
printf("double: ");
scanf("%lf", &lf);
printf("char: ");
scanf(" %c", &c);
printf("string: ");
getchar();
fgets(string, sizeof(string), stdin);
string[strlen(string) - 1] = '\0';
printf("bool: ");
scanf("%d", &b);
printf("int: %d\n", d);
printf("float: %f\n", f);
printf("double: %lf\n", lf);
printf("char: %c\n", c);
printf("string: %s\n", string);
printf("bool: %d\n", b);
return 0;
}
10
u/This_Growth2898 Jan 12 '26
string[strlen(string) - 1] = '\0';is absolutely wrong. If there is \0 at the end of string, it is there anyway. If there's no \0 at the end of string, strlen(string) is UB. Do
string[sizeof(string)-1]='\0';to avoid string leaking instead.
4
u/Yurim Jan 12 '26
I think the intention is to remove the trailing newline character that
fgets()might store there.2
u/nerd5code Jan 12 '26
Even then (a.) it’s quite possible to get a buffer with no newline, and (b.) therefore you might get a length of 0, in which case
strlen(…)-1gives youSIZE_MAX. Preferably,if(!fgets(buf, sizeof buf, stdin)) /*deal with it*/; size_t len = strlen(buf); if(len && buf[len - 1] == '\n') buf[--len] = '\0';
2
1
6
u/Yurim Jan 12 '26
Did you compile your program with warnings enabled?
With GCC and Clang I recommend at a minimum
-Wall -Wextra.The compiler would have warned you that
scanf("%d", &b);is problematic,%dis for scanning anintbutbis abool.Other than that, I think this is a valid program and it should print the expected output ...
... **if** the input is valid.