I cannot input a character. My program terminates - c

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.

Related

getchar() doesnt wait for enter press [duplicate]

This question already has answers here:
getchar does not stop when using scanf
(5 answers)
Closed 3 years ago.
I started C just a while ago (same as coding), so I`m a noob.
My Goal:
to state that the user hasn't entered a or b and then wait for the user to press enter to return to the calculator menu.
My problem:
getchar() doesn't wait for me to press enter. (Case 3)
#include <stdlib.h>
int main()
{
for (int i = 0;i == 0;){
int options=0,enteredA=0, enteredB=0;
float *a, A, *b, B, *c, C;
a=&A,b=&B,c=&C;
printf ("Calculator\nAvailable options:\n[1]Enter value for A\n[2]Enter value for B\n[3]Addition\n[9]Exit\n");
scanf ("%d",&options);
system ("clear");
switch (options) {
case 1:
printf("Enter a value for A:");
scanf ("%f",&*a);
enteredA++;
break;
case 2:
printf("Enter a value for B:");
scanf ("%f",&*b);
enteredB++;
break;
case 3:
if ((enteredA==0) | (enteredB== 0)){
printf("A and B are not initialized yet. Please enter a value in the menu.\nPress [Enter] to continue to the menu:\n");
fflush(stdin);
getchar();
break;
} else{
printf("%f+%f=%f\n",*a,*b,*c=*a+*b);
fflush(stdin);
getchar();
break;
}
break;
case 9:i++;break;
}
system("clear");
}
printf("Calculator Shut Down");
return 0;
}
In the following line:
scanf ("%d",&options);
you actually enter a number, and a newline character. The scanf function reads only the number. It leaves the newline (\n) in the input stream.
When you call getchar(), it will find a newline in the input stream. Hence, it will read it without waiting for user input. It only wait for user input if it didn't find anything in the input stream.
A possible workaround for this is to call getchar two times instead of one.
The first call will read the already existing newline in the stream. The second call won't find anything in the input stream. So, it will wait for user input as you expect.
I have some small comments that aren't related to your question:
You use scanf ("%f",&*a);. Why not just scanf("%f", a); or scanf("%f", &A); ?
Why you even create a pointer a for the variable A ?
I don't think you really need the variable c as well.
You don't need the variable i in the loop as well.
At the beginning of the loop, you keep re-initializing enteredA and enteredB variables to zero. That way, the condition in case 3: will be always true. You need to move these variables outside of the loop.
Your code also missing a #include <stdio.h>.
I'd simplify things like the following:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int enteredA = 0, enteredB = 0;
while (1)
{
int options;
float A, B;
printf ("Calculator\nAvailable options:\n[1]Enter value for A\n[2]Enter value for B\n[3]Addition\n[9]Exit\n");
scanf("%d", &options);
getchar(); // The extra getchar to read the newline left in the stdin.
system ("clear");
switch (options)
{
case 1:
printf("Enter a value for A:");
scanf("%f", &A);
enteredA++;
break;
case 2:
printf("Enter a value for B:");
scanf ("%f", &B);
enteredB++;
break;
case 3:
if (enteredA ==0 || enteredB == 0)
{
printf("A and B are not initialized yet. Please enter a value in the menu.\nPress [Enter] to continue to the menu:\n");
}
else
{
printf("%f + %f = %f\n", A, B, A + B);
}
getchar();
break;
case 9:
printf("Calculator Shut Down");
return 0;
}
system("clear");
}
}

getchar and scanf not works properly in c

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;
}

C Programming help - Option for user to exit program

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.

calling main function in C

#define f(x) (x*(x+1)*(2*x+1))/6
void terminate();
main()
{
int n,op;
char c;
printf("Enter n value\n");
scanf("%d",&n);
op=f(n);
printf("%d",op);
printf("want to enter another value: (y / n)?\n");
scanf("%c",&c); // execution stops here itself without taking input.
getch();
if(c=='y')
main();
else
terminate();
getch();
}
void terminate()
{
exit(1);
}
In the program above , I want to take input from the user until he enters an n value.
For this I'm trying to call main() function repeatedly . If it is legal in C , I want to know why the program terminates at the scanf("%c",&c) as shown in commented line.
Someone , please help.
You should never call main from within your program. If you need to run it more then once use a while loop inside it.
Your execution stops because by default stdin in a terminal is line buffered. Also you are not using the return value from getch.
int main()
{
int n,op;
char c;
do {
printf("Enter n value\n");
scanf("%d",&n);
op=f(n);
printf("%d",op);
printf("want to enter another value: (y / n)?\n");
scanf("%c",&c);
} while (c == 'y')
return 0;
}
You first have
scanf("%d",&n);
which you have to press the Enter key for it to accept the number.
Later you have
scanf("%c",&c);
There is a problem here, which is that the first call to scanf leaves that Enter key in the input buffer. So the later scanf call will read that.
This is easily solved, by changing the format string for the second scanf call just a little bit:
scanf(" %c",&c);
/* ^ */
/* | */
/* Note space here */
This tells the scanf function to skip leading whitespace, which includes newlines like the Enter key leaves.
It's legal, but you'll have a STACKOVERFLOW after a while (pun intended).
What you need is a loop:
while (1) {
printf("Enter n value\n");
scanf("%d",&n);
op=f(n);
printf("%d",op);
printf("want to enter another value: (y / n)?\n");
scanf("%c",&c); // execution stops here itself without taking input.
getch();
if(c != 'y')
break;;
}

Loop skips a scanf statement after the first time

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].

Resources