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].
Related
I have an assignment in C language that requires to ask users to enter values to arrays. My idea is createing two different arrays which one contains integer values and the other holds character values. This is my code so far:
#include <stdio.h>
int main()
{
char continued;
int i = 0;
char instrType[10];
int time[10];
printf("\nL-lock a resource");
printf("\nU-unlock a resource");
printf("\nC-compute");
printf("\nPlease Enter The Instruction Type");
printf(" and Time Input:");
scanf("%c", &instrType[0]);
scanf("%d", &time[0]);
printf("\nContinue? (Y/N) ");
scanf("%s", &continued);
i = i + 1;
while (continued == 'Y' || continued == 'y')
{
printf("\nL-lock a resource");
printf("\nU-unlock a resource");
printf("\nC-compute");
printf("\nPlease Enter The Instruction Type ");
printf("Time Input:");
scanf("%c", &instrType[i]);
scanf("%d", &time[i]);
printf("\nContinue? (Y/N) ");
scanf("%s", &continued);
i = i + 1;
}
return 0;
}
The expected value should be: L1 L2 C3 U1
My Screenshot
The loop just stopped when I tried to enter new values and the condition did not check the value even I entered 'Y' meaning 'yes to continue' please help :(
You are comparing a string with a character that is instead of using scanf("%s",&continued) try using "%c"
The main problem is scanf("%c", &char) because scanf() after had read the input print a \n to pass at the next line, this cause that the next scanf() instead of reading your input, go to read \n, causing the failure in the reading of the input.
To avoid this problem put a space before %c ==> scanf(" %c", &char)
#include <stdio.h>
int main()
{
char continued;
int i = 0;
char instrType[10];
int time[10];
do
{
printf("L-lock a resource\n");
printf("U-unlock a resource\n");
printf("C-compute\n");
printf("Please Enter The Instruction Type and Time Input: ");
scanf(" %c%d", &instrType[i], &time[i]);
printf("Continue? (Y/N) ");
scanf(" %c", &continued);
i++;
} while (continued == 'Y' || continued == 'y');
return 0;
}
Other things:
Instead of i = i + 1 you can use i++
Instead of using a while() is better using a do{...}while() for saving some line of code.
You can concatenate more inputs in a single line ==> scanf(" %c%d", &instrType[i], &time[i])
This question already has answers here:
Using fflush(stdin)
(7 answers)
Parsing input with scanf in C
(5 answers)
scanf() leaves the newline character in the buffer
(7 answers)
Closed 5 years ago.
#include <stdio.h>
int main()
{
char another;
int num;
do
{
printf("enter the number");
scanf("%d", &num);
printf("square of%d is %d\n", num, num * num);
printf("want to check another number y/n");
fflush(stdin);
scanf("%c", &another);
} while (another == 'y');
return 0;
}
In the above code, the second scanf() is not getting executed and hence the console is not accepting input.
According to the standard, flushing stdin is undefined behaviour. See Using fflush(stdin) for more information.
When you enter a number for the first scanf, its always followed by a newline. %d only takes the integer value and the newline is still left in the input buffer. So the subsequent scanf ends up consuming that character and your loop terminates due to another=='y' being false. (another has '\n').
Following is one of the ways to solve the problem. Use a %c along with %d to capture newline and ignore it.
#include<stdio.h>
int main()
{
char another, nl;
int num;
do
{
printf("enter the number");
scanf("%d%c",&num,&nl);
printf("square of%d is %d\n",num,num*num);
printf("want to check another number y/n: ");
//fflush(stdin);
scanf("%c",&another);
printf("%c", another);
}while (another=='y');
return 0;
}
if you add the statement
fseek(stdin, 0, SEEK_END);
it will move the stdin pointer to the end of the file so any extra character will be omitted. then write the second scanf. I mean:
#include<stdio.h>
int main()
{
char another, nl;
int num;
do
{
printf("enter the number");
scanf("%d%c",&num,&nl);
fseek(stdin, 0, SEEK_END);
printf("square of%d is %d\n",num,num*num);
printf("want to check another number y/n: ");
//fflush(stdin);
scanf("%c",&another);
fseek(stdin, 0, SEEK_END);
printf("%c", another);
}while (another=='y');
return 0;
}
Cause of the char input before scanf dont work
remove the fflush and add a space to <<"%c">>
like this: scanf(" %c",&another);
#include<stdio.h>
int main(){
char another;
int num;
do
{
printf("enter the number ");
scanf("%d",&num);
printf("square of %d is %d\n",num,num*num);
printf("want to check another number y/n ");
scanf(" %c",&another);
}while (another=='y');
return 0;
}
This works great
First of all fflush; flushes the output buffer of a stream, so you should not be using it here. The reason why the second scanf is not working is because you are trying to read a 1-bit character which in this case always getting the value of \0 after the second printf statement. Hope this helped.
I'm having an issue in the following code:
int main()
{
char choice;
char secondChoice;
int howMany = 0;
printf("WHAT WOULD YOU LIKE TO ORDER?\n F- fruitShake\n M- milkShake\n");
choice = getchar();
printf("WHAT SIZE?\n B-big\nS-small\n");
secondChoice = getchar();
printf("how many would you like?\n (choose a number between 1-9)\n");
scanf("%d", &howMany);
system("pause");
return 0;
}
After entering the first char (of the what would you like to order) which works properly and right after that both of the printf shows up and it's not working well. (like its skipping on the secondChoice = getchar();)
My guess is that it's not skipping but probably reading the newline character from your previous input(if you used the Enter key to terminate your input).
Please run the modified code added below and observe that program works properly with addition of 2 statements.
fflush(stdout);
fflush(stdin);
Take note while using fflush (stdin) as some sources that i referred to advise not to use it. You may try removing the fflush(stdin) statement and notice the difference in your output
int main()
{
char choice;
char secondChoice;
int howMany = 0;
printf("WHAT WOULD YOU LIKE TO ORDER?\n F- fruitShake\n M- milkShake\n");
fflush(stdout);
choice = getchar();
fflush(stdout);fflush(stdin);
printf("WHAT SIZE?\n B-big\n S-small\n");
fflush(stdout);fflush(stdin);
secondChoice = getchar();
printf("how many would you like?\n (choose a number between 1-9)\n");
fflush(stdout);fflush(stdin);
scanf("%d", &howMany);
printf("\nChoice = %c\nsecondChoice = %c \nhowMany = %d\n\n", choice, secondChoice, howMany);
fflush(stdout);
system("pause");
return 0;
}
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);
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why doesn't getchar() wait for me to press enter?
I continue to learn C, and at this stage I have something that is not clear to me.
When I write a program, that has several printf();, at the end, where I ask a user to press Enter key to finish the program, I have to write getchar(); twice, because when I write it once it does not work. I use getchar(); only at the end of the program, nowhere else.
I work on Ubuntu. I write in C.
here is my latest work:
#include<stdio.h>
main()
{
int m,n,r,k,q,l;
printf("This program will help you to find GCD & LCM of 2 non-negative integers\n");
printf("Now, you'll be asked to enter your integers, press Enter to continue");
getchar();
printf("Enter first integer:");
scanf("%i", &m);
printf("Enter second integer:");
scanf("%i", &n);
while(m<0 || n<0)
{
printf("The integers cannot be negative! You'll be asked to enter integers again.\n");
printf("Enter first integer:");
scanf("%i", &m);
printf("Enter second integer:");
scanf("%i", &n);
}
while(m==0 && n==0)
{
printf("Both of the integers cannot be zero at the same time! You'll be asked to enter integers again.\n");
printf("Enter first integer:");
scanf("%i", &m);
printf("Enter second integer:");
scanf("%i", &n);
}
if(n>m)
{
int b;
b=n;
n=m;
m=b;
}
r=m%n;
if(r==0)
{
printf("The GCD of these integers is %i\n", n);
printf("The LCM of these integers is %i\n", m);
printf("Press Enter to finish");
getchar();
getchar();
return 0;
}
k=n%r;
while(k>0)
{
r=k;
k=q;
}
l=(m*n)/r;
printf("The GCD of these integers is %i\n", r);
printf("The LCM of these integers is %i\n", l);
printf("Press Enter to finish");
getchar();
getchar();
return 0;
}
The reason you need 2 getchar() is because
the last scanf() call left the ENTER waiting in the buffer
the 1st getchar() "ate" that ENTER
the 2nd getchar() waits for input.
To properly deal with user input, use fgets() and sscanf() instaed of the simpler scanf(). Define a buffer for these functions, for example
char buffer[1000];
and then replace your scanf() calls with the pair
fgets(buffer, sizeof buffer, stdin);
sscanf(buffer, "%d", &n);
In the future you might want to also check the return value of sscanf() to detect invalid inputs, like foo42ENTER
if (sscanf(buffer, "%d", &n) != 1) /* invalid input */;
Edit (using strtol() rather than sscanf() is even better -- thanks to #Scooter)
char buffer[1000];
char *err;
/* ... */
fgets(buffer, sizeof buffer, stdin); /* error checking ommited */
n = strtol(buffer, &err, 10);
/* error checking ommited */
/* ... */