0

I have the following code, but why doesn't the second while loop run? Any changes to make it run?

#include<stdio.h>
int main() {
    int a,b,c,d,e,f;
    while(scanf("%d,%d,%d",&a,&b,&c)==3){
        printf("ok\n");
    }
    while(scanf("%d,%d,%d",&d,&e,&f)==3){
        printf("OK\n");
    }
    return 0;
}

My input is

1,2,3
1,5,7,4,8,7
7,8,9,...
13
  • Please specify what input are you providing Commented Mar 13, 2021 at 11:17
  • 1,2,3(press enter) 1,5,7, stops at this point but needs to take the input 4,8,7 (press enter) 7,8,9,.. Commented Mar 13, 2021 at 11:19
  • 1
    the second loop won't run until the first one is running. try to enter less numbers and see that the first loop will stop and the second will run. Commented Mar 13, 2021 at 11:22
  • when it enter a,b,c it keeps running but when I enter a,b,c, it will stop and second while should run but it's not running Commented Mar 13, 2021 at 11:24
  • 1
    Re "when I enter a,b,c, it will stop and second while should run but it's not running", That's because you have ,4,8,7 but your pattern expects 4,8,7 Commented Mar 13, 2021 at 11:28

1 Answer 1

1

Let's say you input "1,5,7,4,8,7<ENTER>" for the scanf() in the 1st while.

The scanf("%d,%d,%d", &a, &b, &c); reads 1 into a, 5 into b, 7 into c and returns 3 keeping ",4,8,7<ENTER>" in the input buffer.

In the 2nd time through the loop, scanf finds the comma and returns 0 which terminates the while.

Immediately after that, in the 2nd while, the 2nd scanf() attempts to convert ",4,8,7<ENTER>" to an integer and fails promptly returning 0 and terminating the while.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.