0

I was meant to write a program so that it prints the number of stars. Example

Enter numbers : 12 11 9 8 ^D

12 | ************
11 | ***********
9 | *********
8 | ********

#include <stdio.h>

int main(int argc, char *argv[]) {
int a;
printf("enter values \n");

while (scanf("%d ", &a) != EOF) {

    printf("%d |", a);

    for (int j = 1; j<= a; j++) {
        printf("*");
    }
    printf("\n");
}

}

With my code it prints out the right output but it doesn't print out the number of stars for the last value I enter. Like in the above example it wont print out 8 stars until I hit the enter again or press ^D. I was wondering is there somethign wrong with my code. ?

dave_1234
  • 147
  • 1
  • 3
  • 10

2 Answers2

0

No there is nothing wrong with your code.

stdin is line-buffered, so input can't be read until you press or (=ctrl-d in Linux).

There are libraries such as conio.h that provide non-buffered input.

Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82
  • But shouldn't it print them when I press enter. ?? It doesn't print the last one till I press cntrl+D – dave_1234 Aug 31 '15 at 14:01
  • `stdout` is normally line buffered when connected to a terminal, so the `printf("\n");`should flush the output to the screen. You can try adding `fflush(stdout);` to programmatically flush the output buffer. – Klas Lindbäck Aug 31 '15 at 14:17
0

Remove the trailing space after %d inside scanf("%d ", &a)).

#include <stdio.h>

int main(int argc, char *argv[]) {
    int a;
    printf("enter values \n");

    while (scanf("%d", &a) != EOF) {

        printf("%d |", a);

        for (int j = 1; j<= a; j++) {
            printf("*");
        }
        printf("\n");
    }
    return 0;
}
Rafaf Tahsin
  • 7,652
  • 4
  • 28
  • 45