Tricolor Tricolor - 2 months ago 17
C Question

Keeping leading spaces in C

I'm having this simple problem that I can't get over with.

int B;
char *a = (char*)malloc(1000*sizeof(char);

scanf("%[^\n]s", a);
printf("%c\n", a[0]);
B = strlen(a);
printf("%d\n", B);


If I put an entry like:

" abc "


a[0] = 'a' and B = 5 (the "abc" plus the last two spaces). I want to count the first three spaces, how do I do it?

Thank you!

Answer

You could simply read the entire line using fgets() instead of using scanf(), which generally skips whitespace unless you explicitly capture it.

int B;
char *a = malloc(1000 * sizeof*a); /* don't cast malloc */

if (fgets(a, 1000, stdin) == NULL) {
    fputs("Could not read input\n", stdout);
}
else {
    printf("%c\n", a[0]);
    B = strlen(a);
    printf("%d\n", B);
}
Comments