-1

I have tried to make a simple program in C to count the number of char in a string. But it only counts the first word, if i leave any space it stops

#include <stdio.h>

int main() {
    char str1[100];
    int i = 0, count = 0;
    printf("enter string:\n");
    scanf("%s", str1);
    while (str1[i] != '\0') {
        i++;
        count++;
    }
    printf("total number of char %d", count);
    return 0;
}
Raz
  • 21
  • 2
  • 2
    You may want to read this: [Why not upload images of code/errors when asking a question?](https://meta.stackoverflow.com/q/285551/12149471) – Andreas Wenzel Apr 28 '21 at 12:01
  • 1
    Tip: Investigate what `scanf("%s", ...)` do – Support Ukraine Apr 28 '21 at 12:03
  • 5
    The `%s` `scanf` format specifier will not read an entire line, but only a single word. If you want to read an entire line, I recommend you use [`fgets`](https://en.cppreference.com/w/c/io/fgets) instead. – Andreas Wenzel Apr 28 '21 at 12:03
  • Does this answer your question? [How do you allow spaces to be entered using scanf?](https://stackoverflow.com/questions/1247989/how-do-you-allow-spaces-to-be-entered-using-scanf) – Adrian Mole Apr 28 '21 at 13:32

1 Answers1

1

scanf("%s", str1) reads a single word and leaves the separator (any sequence of white space) and the rest of the input line in the stdin buffer. If you want to count the number of characters in the full input line, use fgets() to read a full line and stop on the newline ('\n') in addition to the end of string ('\0').

Here is a modified version:

#include <stdio.h>

int main() {
    char str1[100];
    int i;

    printf("enter string:\n");
    if (fgets(str1, sizeof str1, stdin)) {
        for (i = 0; str1[i] != '\0'; i++) {
            if (str[i] == '\n') {
                str[i] = '\0';
                break;
            }
        }
        printf("total number of chars: %d\n", i);
    }
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189