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;
}
Related
The program generates a blank space at the first line of the "data.txt" file and also generates a one more serial number.
#include<stdio.h>
#include<string.h>
int main(){
int limit;
int i = 0;
printf("How many approxmiate size of your list will be: \n");
scanf("%d", &limit);
char list[100][100];
FILE *store;
store = fopen("data.txt", "w");
while(i<=(limit - 1)){
printf("Enter task: \n");
gets(list[i]);
fprintf(store,"%s\n%d)",list[i], i+1);
i++;
}
fclose(store);
return 0;
}
It's because the linefeed ('\n') after scanf("%d", &limit); remains in the input buffer, either change scanf("%d", &limit); to scanf("%d ", &limit); or better yet, don't use gets() at all (it's dangerous to use gets(): read the reason here), instead use fgets() or scanf().
So your final code may look like this:
#include<stdio.h>
#include<string.h>
int main(){
int limit;
int i = 0;
printf("How many approxmiate size of your list will be: \n");
scanf("%d", &limit);
char list[100][100];
FILE *store;
store = fopen("data.txt", "w");
while(i<=(limit - 1)){
printf("Enter task: \n");
scanf(" %99[^\n]",list[i]);
fprintf(store,"%s\n%d)",list[i], i+1);
i++;
}
fclose(store);
return 0;
}
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.
Here is my code for my project. It's not yet done because I'm stuck with the last scanf (after printf("Enter option:")). My program terminates after pressing two keys. I also tried char and %c but it didn't work. Hope you can help me.
void main()
{
char user[20], pass[500];
int i, a;
clrscr();
gotoxy(30,7); printf("ACCESS THE SYSTEM");
gotoxy(28,9); printf("Username: ");
gets(user);
gotoxy(28,11); printf("Password: ");
for(i = 0; i< 500; i++)
{
pass[i] = getch();
if(pass[i] == 13)
{
pass[i] = 0;
break;
}
printf("*");
}
gotoxy(30,15);printf("ACCESS GRANTED!");
gotoxy(24,20);printf("Please press any key to proceed: ");
scanf("%d", &a);
topics();
getch();
}
int topics(){
int opt;
clrscr();
gotoxy(25,5);printf("ÉÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ»");
gotoxy(25,6);printf("º Computer Programming Topics: º");
gotoxy(25,7);printf("ÈÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍͼ\n");
gotoxy(13,9);printf("Choose one:");
gotoxy(13,11);printf("[A] Conditional Statements");
gotoxy(13,13);printf("[B] Looping Statements");
gotoxy(13,15);printf("[C] Functions");
gotoxy(13,17);printf("[D] Arrays");
gotoxy(13,19);printf("[E] Strings");
gotoxy(13,22);printf("Enter option:");
gotoxy(13,23);scanf("%d", &opt);
getch();
}
given this code, in main()
gotoxy(24,20);printf("Please press any key to proceed: ");
scanf("%d", &a);
topics();
getch();
the line: `scanf("%d", &a); required the input to end with a 'return' key which puts a newline in the input stream, that is not consumed here.
the topics() function contains a getch() which does get the 'return' key from the input stream.
Note: a 'return' key is not a valid input for the topics() function.
then the user has to input another keystroke for the final getch() in main(). Then the execution runs off the end of main() which results in the program exiting.
Suggest: in main() the line: scanf("%d", &a); be replaced with getch()
The posted code, after calling topics() (which gets a keystroke) then, one more keystroke and the program exits.
If you want the program to continue executing, then the call to topics() needs to be followed by some other code to execute.
I am not too familiar with C syntax. I need to process some data based on user input. Although I processed the data successfully but I am stuck at user input section. I removed the unnecessary data processing section and made a simple example of how I am taking the user input. Can anyone tell me what's the problem with below code :
int i, number;
char *str;
str=(char*)malloc(1000*sizeof(char));
printf("Enter count : ");
scanf("%d", &number);
for(i=0; i<number; i++)
{
printf("\nEnter string: ");
scanf ("%[^\n]%*c", str);
printf("%s", str);
}
Output:
"Enter count : " appears fine, but whenever I provide some value and hit enter it's showing me only 'count' number of Enter string: without enabling user to enter the string.
For example -
Enter count : 2
Enter string:
Enter string:
But if I discard the count input section and provide any fixed value, like
for(i=0; i<5; i++)
it works fine
Thanks in advance
FYI, there is no issue in for(i=0; i<number; i++), problem is in scanning logic.
Actually, scanf ("%[^\n]%*c", str); is not right. you should use %s to read strings, not %c, which reads a single character, including the ENTER (newline).
Rather, i would suggest, use fgets() for inputs. It's a whole lot better in every way. Check the man page here.
Maybe you can use something like
//Dummy code
int i, number;
char *str;
printf("Enter count : ");
scanf("%d", &number);
str=malloc(number*sizeof(char)); //yes, casting not required
fgets(str, (number-1), stdin ); //"number" is used in different context
fputs(str, stdout);
EDIT:
Working code
#include <stdio.h>
#include <stdlib.h>
#define SIZ 1024
int main()
{
int i, number;
char * str = malloc(SIZ * sizeof (char));
printf("Enter the number :\n");
scanf("%d", &number);
getc(stdin); //to eat up the `\n` stored in stdin buffer
for (i = 0; i < number; i++)
{
printf("Enter the string %d :", (i+1));
fgets(str, SIZ-1, stdin);
printf("You have entered :");
fputs(str, stdout);
}
return 0;
}
scanf("%s",str); Use this instead of the code you are using to take string inputs in a character array.
There is a newline character \n after entering count value which is picked up by %c in your scanf()
Just use %s to scan strings as shown below.
scanf("%s",str);
If there are spaces in your input.
Then do
char c[50];
fgets(c,sizeof(c),stdin);
Check the below code:
#include <stdio.h>
#include<stdlib.h>
int main(){
int i, number;
char *str;
str=malloc(1000*sizeof(char));
printf("Enter count : ");
scanf("%d%*c", &number);
for(i=0; i<number; i++)
{
printf("\nEnter string: ");
fgets(str,1000,stdin);
printf("%s", str);
}
}
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].