This question already has answers here:
Simple C scanf does not work? [duplicate]
(5 answers)
Closed 9 years ago.
I have written a simple program to exchange currency and able to buy a beer.
But there something in program and I don't know why, it auto skips the third input data -> end program.
Here my code :
#include <stdio.h>
#include <stdlib.h>
int main()
{
int ex_rate_into_vnd = 20000; //! Exchange Rate
int beer = 7000; //! Local price of a beer
float in_c = 0; //! Input amount of money
float out_c = 2; //! Amount of currency to exchange !
float choice; //! Switch mode
char buy; //! Deal or not
//! Introduction
printf ("||---------------------------------------------------||\n");
printf ("|| Currency Exchange Machine beta ||\n");
printf ("||---------------------------------------------------||\n");
printf ("Please choose your option:\n");
printf("\t 1.Exchange VND to dollar\n");
printf("\t 2.Exchange Dollar to VND\n");
do
{
printf("Your choice: ",choice);
scanf("%f",&choice);
} while( choice != 1 && choice != 2);
printf ("Please enter amount of money:");
scanf("%f",&in_c);
if (choice == 1 )
{
out_c = in_c / ex_rate_into_vnd;
printf ("Your amount of money: %.2f",out_c);
}
else
{
out_c = in_c * ex_rate_into_vnd;
printf ("Your amount of money: %.0f",out_c);
}
//! End of Exchanging
printf ("\nWould you like to buy a beer (y/n) ?",buy);
scanf("%c", &buy);
if (buy == 'y')
{
if (out_c >= 7000)
{
out_c = out_c - 7000;
printf("Transactions success !\n");
printf("Your amount: %2.f",out_c);
}
}
printf ("\nWhy Stop ?");
return 0;
}
You have at least one \n between the latest float entry and the char you want to read. You need to get rid of that first.
See also all answers in getchar after scanf category
Change
scanf("%c", &buy);
to
scanf(" %c", &buy);
// ^space
Because the newline character is still in the input buffer after you enter a number and press ENTER in the second scanf.
Instead of scanf("%c", &buy);
1.use space before %c
scanf(" %c",&buy); //space before %c
^
this skips reading of white space (including newlines).
2.or Use getchar(); before scanf("%c", &buy); statement
getchar(); //this hold the newline
scanf("%c", &buy);
3.or use two times getchar();
getchar();
buy=getchar();
//here getchar returns int , it would be better if you declare buy with integer type.
In GCC usage of fflush(stdin); is discouaraged. please avoid using it.
I was wondering why you made 'choice' a float, not an int
Also, consider using a switch-case
that way, you won't have to do the whole do-while loop.
Also, in the line
printf ("\nWould you like to buy a beer (y/n) ?",buy);
Why did u add that?
Here is what I would have done :
printf("Your choice?\n>");
scanf("%d", &choice);
switch(choice)
{
case 1 :
{
out_c = in_c / ex_rate_into_vnd;
printf ("Your amount of money: %.2f",out_c);
}
case 2:
{
out_c = in_c * ex_rate_into_vnd;
printf ("Your amount of money: %.0f",out_c);
}
default :
printf("\nThere has been an error\n"):
reloadprogram(); /* Reloadprogram() is simply to make this go back to the asking thing :) */
}
}
EDIT: also, where it says if( <somevariable> >= 7000), change 7000 to beer, so that way, if u change beer, you won't have to change this :)
Put a fflush(stdin) to clear the input before the last scanf
The program doesn't skip the third input data, it just scans the newline you press after the second input. To fix this, type scanf("%*c%c", &buy); instead of scanf("%c", &buy);. This little %*c scans and ignores the the character read from the input.
you can remove the buy variable from the printf call, it's unneeded
printf ("\nWould you like to buy a beer (y/n) ?",buy);
And replace char buy by char buy[2]; . because a sting is always terminated by /0.
You can also add a memset (buy, 0, sizeof(buy)), to be sure that memory is reset before you start to use it.
Related
Hi I am new to programming and I got a trouble when I try to make a little change to the example in the book.
/* Chapter 3 Example, C Prime Plus */
#include <stdio.h>
int main(void)
{
char Letter, ch;
int intValue;
printf("Please enter a letter: \n");
scanf("%c", &Letter); /* user inputs character */
printf("The code for %c is %d.\n", Letter, Letter);
printf("Now is another we to implement the process: \n");
printf("RN, the value of ch is %c, and the value of intValue is %d\n", ch, intValue);
printf("Please enter a letter: \n");
scanf("%c", &ch);
intValue = ch;
printf("The code for %c is %d.\n", ch, intValue);
return 0;
}
When I run it, the outcome would be
Please enter a letter:
M
The code for M is 77.
Now is another we to implement the process:
RN, the value of ch is , and the value of intValue is 0
Please enter a letter:
The code for
is 10.
and the part
"
Now is another we to implement the process:
RN, the value of ch is , and the value of intValue is 0
Please enter a letter:
The code for
is 10. " will all come out without asking me to enter a value.
I want to know why and are there any other way to implement it that is different from examples in the book?
Thank you for your time!
Hi Matt_C and welcome to SO.
First, you don't need the second bloc of printfs and the scanf, it just trying to do the same thing and there is an order error.
Second, it is tricky when you try consecutive scanf, it holds the last key pressed (enter is the last key pressed = \n). This is why it skips the second scanf.
There a little solution for that, add a space at the beginning of the scanfs. Try this:
int main() {
char exit, letter;
while (1) {
printf("Please enter a letter: ");
scanf(" %c", &letter);
printf("\nThe code for '%c' is %d. \n\n", letter, letter);
printf("Exit ? (y/n): ");
scanf(" %c", &exit);
if(exit == 'y')
{
break;
}
system("clear"); // UNIX
//system("cls"); // DOS
}
}
Don't forget to choose one answer that you believe is the best solution to your problem.
I'm writing a basic C program that will convert either Celsius or Fahrenheit to the other.
I have a scanf statement where the user enters the temperature they want to convert, and then a printf statement asking for whether that temperature was in c or f.
when I compile, the scanf asking for char c or f is instead grabbing the \n from the previous scanf. according to my debugger.
the code looks like this:
int celcius(void){
double originalTemp = 0;
double newTemp;
char format;
printf ("enter a temperature: ");
scanf ("%lf",&originalTemp); //what is the original temp?
printf ("enter c if in celcius, enter f if in ferenheit: "); //enter c or f
scanf("%c", &format); //why do I need to do this twice??, this one grabs \n
scanf("%c", &format); //this one will pick up c or f
if (format == 'c'){
newTemp = originalTemp*1.8+32;
printf("%.2lf degrees Farenheit\n", newTemp);
} //convert the Celcius to Ferenheit
else if (format == 'f'){
newTemp = (originalTemp-32)/1.8;
printf("%.2lf degrees Celcius\n", newTemp);
} //convert the Ferenheit to Celcuis
else {
printf ("ERROR try again.\n");
} //error if it isn't f or c
return 0;
}
am I missing something? I know thatscanf looks in the input stream for the next char in this case, but why is \n still in the input stream at this point?
and is there a "proper" way to fix this other than get char?
Space in the format string matches whitespace, so you can just match away/skip the cr/lf;
printf ("enter c if in celcius, enter f if in ferenheit: "); //enter c or f
scanf(" %c", &format); // get next non white space character, note the space
if (format == 'c'){
The rule is to write a getchar() after every integer/float/double input if you take char/string inputs later. This getchar() flushes out the \n from the input buffer which is leftover by taking the integer/float/double input.
So just write a getchar(); after scanf ("%lf",&originalTemp); and you'll be fine.
this is a follow on question from one I asked recently:
C Programming help - providing user with option to exit a program
I now have a new problem. I can get the program to exit if a user enters any letter which is great, but now if a number is entered nothing happens. The while loop doesn't seem to run..
Can you please have a look at my code and see if you can spot what's wrong, thanks. Also, ideally i'd like xterm's window to close if the user wishes to exit. I'd be greatful if anyone could show me how to do this. Anyway here's the code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
float number;
float sum = 0;
printf ("Please enter number or enter any letter to exit:\n");
scanf ("%f", &number);
// if user ENTERS a letter, program will terminate
if(1!=scanf ("%f", &number))
{
getchar();
printf ("Exiting the program...\n");
exit(0);
}
while (1)
{
sum += number;
printf ("Sum: %.2f\n", sum);
printf ("Please enter number or enter any letter to exit:\n");
scanf ("%f", &number);
// if user ENTERS a letter, program will terminate
if(1!=scanf ("%f", &number))
{
getchar();
printf ("Exiting the program...\n");
exit(0);
}
}
return 0;
}
As #BrianCain commented: you are calling scanf a second time in your if statement. If you entered a letter for the first scanf, it forces the second to immediately fail; if you entered a number for the first, then the second is waiting for you to enter another number.
I removed two of your scanf functions and it seems to fix the problem
#include <stdio.h>
#include <stdlib.h>
int main()
{
float number;
float sum = 0;
printf ("Please enter number or enter any letter to exit:\n");
// if user ENTERS a letter, program will terminate
if(1!=scanf ("%f", &number))
{
getchar();
printf ("Exiting the program...\n");
exit(0);
}
while (1)
{
sum += number;
printf ("Sum: %.2f\n", sum);
printf ("Please enter number or enter any letter to exit:\n");
// if user ENTERS a letter, program will terminate
if(1!=scanf ("%f", &number))
{
getchar();
printf ("Exiting the program...\n");
exit(0);
}
}
return 0;
}
The scanf in your if erased the value of the previous one you did.
While the previous two answers are essentially correct, the simple (and clear) version would be:
if(number == 1)
break;
Place this right after your original scanf() and get rid of the other if(..) ..; condition entirely. This will test to see if the number '1' was entered, and if so will break the infinite loop, allowing the program to continue down to the return 0; statement.
It will also deal with what could be confusing style, which is having an exit condition (the final return 0;) that's essentially impossible to get to, or should be.
Here is the code for main():
int main (void)
{
float acres[20];
float bushels[20];
float cost = 0;
float pricePerBushel = 0;
float totalAcres = 0;
char choice;
int counter = 0;
for(counter = 0; counter < 20; counter++)
{
printf("would you like to enter another farm? ");
scanf("%c", &choice);
if (choice == 'n')
{
printf("in break ");
break;
}
printf("enter the number of acres: ");
scanf("%f", &acres[counter]);
printf("enter the number of bushels: ");
scanf("%f", &bushels[counter]);
}
return 0;
}
Every time the program runs through the first scanf works fine but on the second pass through the loop the scanf to enter a character does not run.
Add a space before %c in scanf. This will allow scanf to skip any number of white spaces before reading choice.
scanf(" %c", &choice); is the only change required.
Adding an fflush(stdin); before scanf("%c", &choice); will also work. fflush call will flush the contents of input buffer, before reading the next input via scanf.
In case of scanf(" %c", &choice); even if there is only a single character in the input read buffer, scanf will interpret this character as a valid user input and proceed with execution. Incorrect usage of scanf may result in a series of strange bugs [like infinite loops when used inside while loop].
This question already has answers here:
Scanf skips every other while loop in C
(10 answers)
Closed 8 years ago.
#include "stdio.h"
int main(void)
{
int order, nextp, N=3;
char cont;
nextp = 0;
printf("\nShould we continue (y or n): ");
scanf("%c", &cont);
if (cont != 'y') return;
for(; nextp < N; nextp++)
{
printf("Enter order number: ");
scanf("%d", &order);
printf("you have entered %d\n", order);
printf("okay now continue with cont\n");
printf("enter cont y or n: ");
scanf("%c", &cont);
if (cont != 'y')
{
printf("\nnot equal to y\n");
break;
}
printf("after intepreting t[0]");
}
return 0;
}
The output looks like this
Should we continue (y or n): y
Enter order number: 45
you have entered 45
okay now continue with cont
enter cont y or n:
not equal to y
The second input was skipped. Why?
because of newline character already in stdin , this is happening.
use
scanf(" %c", &cont);
instead of
scanf("%c", &cont);
note one space before %c.
After scanf("%d", &order); consumes the number (45 in this case), there is still a newline left after that. You can use scanf("%d\n", &order) to make it consume the return.
Another answer to this can be found here:
scanf() leaves the new line char in buffer?
This is why scanf is not typically preferred for character input. There's a left over carriage return after the previous input.
For example, if you were to add a getchar() after the order input, your problem would be solved, but that's not clean code. You can also see this explicitly by subsituting cont != 'y' to cont != '\n'.
Instead, use getchar() for all your input and check for \n
For most conversions scanf will skip whitespace, but for char format ("%c") you must skip white space by using an explicit space in the format (" %c") as explained here:
C - trying to read a single char
This is also explained in the scanf documentation, but it's confusing and may be better to use something else as others have mentioned.
You can use fflush()
printf("enter cont y or n: ");
fflush(stdin);
scanf("%c", &cont);