Gabriel Antunes
Gabriel Antunes

Reputation: 11

My 'scanf' loop doesn't stop; while condition is not working

I was supposed to do this exercise: Write a program in C to print a frequency chart on the screen. Input and output: The program receives as input a sequence of triples (number, frequency, character). For each sequence it should print a slash, producing a graph as in the example below.

Example For input

(5,12, -) (4,17, -) (2,1, -) (1,19, +)

the program should print

  5 | ------------ 12
  4 | ----------------- 17
  2 | -
  1 | +++++++++++++++++++ 19

I realize that if I put a space before the sentence in the scanf function, it works very well, but the program desdon't end when it was expected

int main()
{
    int x, b, i, u;
    char n;

    do{
        u = scanf(" (%d,%d,%c)", &x, &b, &n);
        printf("%d |", x);
        for (i = 0; i < b; i++){
            printf("%c", n);
        }
        printf(" %d\n", b);
    }while(u == 3);
}

It was expected that, when the scanf don't read the 3 things it was supposed to, the while loop ends and the program is finished. But, when it happens, he still waiting for a new input. How do I fix that?

Upvotes: 0

Views: 707

Answers (1)

Dhiraz Gazurel
Dhiraz Gazurel

Reputation: 104

just check for the returned value of u and then use an if condition. This shold stop the while loop and exit the program

int main()
{
int x, b, i, u;
char n;


do{
    u = scanf(" (%d,%d,%c)", &x, &b, &n);
    if(u == 3){
        printf("%d |", x);
        for (i = 0; i < b; i++){
            printf("%c", n);
        }
        printf(" %d\n", b);
    }

}while(u == 3);

Upvotes: 1

Related Questions