jchang
jchang

Reputation: 31

Getting a different value than expected runs in a loop. Why?

So, this program accepts three values, an int, a float and a char while being inside a loop. When it asks the user to enter the integer and they write.. let's say, "House" the program falls in an infinite loop.

    #include <stdio.h>

int main(void){

    int i;
    float f;
    char c;

    while(i!=99){

        printf("Enter an int, a float and a char separated by commas: ");
        int count = scanf("%d,%f,%c",&i,&f,&c);
        printf("Int is: %d, Float is: %1.f, Char is: %c",i,f,c);

        if (count != 2){
            fflush(stdin);
            printf("\nerror\n");
        }

    }

    return 0;
}

Upvotes: 0

Views: 55

Answers (2)

ameyCU
ameyCU

Reputation: 16607

In this -

if (count != 2){
        fflush(stdin);                  // undefined behaviour
        printf("\nerror\n");
    }

Also count should be tested against 3 not 2 (scanf will return 3 if successfull ). Instead of fflush(stdin) , use this to clear input stream-

int c;
if (count != 3){
   while((c=getchar())!='\n' && c!= EOF);
  printf("\nerror\n");
}

Also you have i uninitialized. So ,either initialize it or instead of using while loop use do-while -

do{
   //your code
  }while(i!=99);

Upvotes: 1

MikeCAT
MikeCAT

Reputation: 75062

  • scanf() leave characters which aren't interpreted as data to read, so in next iteration, scanf() try to read the characters again and fail again, then it will cause endless loop.
  • fflush(stdin); is undefined behavior and do not use it.
  • Uninitialized i is used in i!=99, which is also undefined behavior.

Try this:

#include <stdio.h>

int main(void){

    int i=0;
    float f=0.0f;
    char c=' ';

    while(i!=99){

        printf("Enter an int, a float and a char separated by commas: ");
        int count = scanf("%d,%f,%c",&i,&f,&c);
        printf("Int is: %d, Float is: %1.f, Char is: %c",i,f,c);

        if (count != 3){ /* adjusted to match the scanf */
            int dummy;
            while((dummy=getchar())!='\n' && dummy!=EOF); /* skip one line */
            printf("\nerror\n");
            if (dummy == EOF) break; /* there won't be any more input... */
        }

    }

    return 0;
}

Upvotes: 1

Related Questions