[SOLVED] Need a new set of eyes on this simple yet troubled C code. Total noob here

I’m just doing an exercise where the user inputs two things: an integer and a float. Print back to them what they typed in then end the program. The input must be done with one line of code.

I keep getting an alert that my program may have an infinite loop. I’ve gone back and forth between the book to check rules for scanf and make sure I’m not breaking them…

I have no idea what would cause an infinite loop…seeing as how I’m not looping anything lol. What silly mistake have I made?

#include <stdio.h>

int main (void)
{
int quantity = 0;
float unitPrice = 0.0;

printf("Welcome. Please enter a quantity first and then a price\n");
scanf(" %d %f\n", &quantity, &unitPrice);
printf("%d %f\n", quantity, unitPrice);
printf("We are done here\n");

return 0;

}

It’s telling you that executing your program took too long and is trying to be helpful by suggesting that the cause might be an infinite loop. But it isn’t.

In reality the program doesn’t terminate because it’s waiting for user input. If you provide input it should execute just fine.

EDIT: I just noticed there’s a superfluous \n in your scanf. Change the line to

scanf("%d %f", &quantity, &unitPrice);

Thanks.

The weird thing is that it never prints the following to monitor. So, it’s not even getting to the scanf part. Right?

printf(“Welcome. Please enter a quantity first and then a price\n”);

It does print the text for me.

Printing is kinda tricky, because C doesn’t have to print output right away. To increase performance it is allowed for the print function to buffer the string and only display it once enough bytes have accumulated.

It is however common to print once a newline is encountered. So if you really don’t see the message that’s odd. You can always force the output manually though:

fflush(stdout);
1 Like

Figured it out.

sneaky

Had to turn on “Interactive mode” lol never seen this before. Thanks for your help.

1 Like