-1

I have this C code:

#include <stdio.h>

int main() {
    char text[] = "Some random text";
    int counter = 0;
    for(int i=0; i < sizeof text / sizeof (char); i++) {
        printf("%c", text[i]);
        counter++;
    }
    printf("\n%d", counter);
}

But the VSCode console only shows the text ("Some random text"). The printf for 'counter' is not working.

If I execute it out of VSCode, by clicking the .exe file, it works fine (in DevC++ too). Any idea?

Sourav Ghosh
  • 127,934
  • 16
  • 167
  • 234
gonza5913
  • 9
  • 1

1 Answers1

1

The printf() function is buffered, you need a new line or fflush(stdout) to flush it.

Just try

printf("\n%d\n", counter);

instead.

Iharob Al Asimi
  • 51,091
  • 5
  • 53
  • 91
  • 1
    Sorry, this not work. I add a fflush(stdout) and some '\n' and didn't work. Same result – gonza5913 Aug 06 '20 at 14:48
  • I didn't see your loop, you are including the null terminator. `sizeof(char) == 1` by definition, and `sizeof` doesn't give you the length of the string, but the length of the array of characters. Literal strings have on extra implied item, namely the 0 terminator. You should subtract 1 or use `for (int i = 0; text[i] != '\0'; ++i)` – Iharob Al Asimi Aug 06 '20 at 16:23
  • Great, thats works! I'm really sorry for the sizeof (char). I did an example with integer's array and i forgot to deleted it. Thanks! – gonza5913 Aug 07 '20 at 13:19