Cody Cody - 1 month ago 5
C Question

C: Unable to receive input using scanf()


int main()

float p, r, t;
char ch = 'y';

printf("Enter principal: ");
scanf("%f", &p);

printf("Enter rate: ");
scanf("%f", &r);

printf("Enter t: ");
scanf("%f", &t);

printf("SI = %f", (p *r * t)/100 );

printf("\nCalculate SI one more time ? ('Y' for Yes, 'n' for no ) : ");
ch = getchar();

}while(ch == 'y');

return 0;



Enter principal: 1334
Enter rate: 4
Enter t: 2
SI = 106.720000
Calculate SI one more time ? ('Y' for Yes, 'n' for no ) :
Process returned 0 (0x0) execution time : 5.359 s
Press any key to continue.

As you can see i am unable to calculate SI second time ?? What is the problem ?

I even tried replacing getchar() by scanf() but it is still not working


scanf stops reading when the number is complete (at the first char that cannot be a part of it).

So the last of your scanf (for t) stops reading just before the RET you pressed after typing t's value. The getchar() then reads the next char, which is a '\n' (the RET), and that is not equals to 'y', so it ends.

You should not mix multiple input methods; if you use scanf, stay with scanf, and have it read one char (scanf("%1s",&ch);) or some other solution; or read the '\n' with an extra getchar() after the scanf and ignore it.