This C program does not work properly if I enter letters - c

If I enter numbers everything works fine. If I enter letters the program no longer works. What am I doing wrong?
P.s. Then I will connect other programs in the form of functions and I want them to be able to run from the menu and then return to the selection menu again
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
main ()
{
int a;
do {
printf("Enter number of programm: \n 1) First programm \n 2) Second programm \n 3) Third programm \n ");
scanf("%d", &a);
switch (a){
case 1: printf("Start My first programm \n"); break;
case 2: printf("Start My second programm \n"); break;
case 3:printf("Start My third programm \n"); break;
default: printf("There is no such program \n"); break;
}
} while (a != -1);
}

The problem is that scanf("%d", &a) only gets numbers because
a. int a can only store numbers and
b. "%d" only gets numbers
To get letter and number input you can do this:
char a[100];
fgets(a, sizeof(a), stdin); // Store input in a, read the buffer until sizeof(a), and finally read from stdin
However, you cannot compare strings in a switch so you will have to use if statements and strcmp from string.h

Related

C program, getting the integer value of a character. Why everything comes out after line 10?

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.

Why c programme code is not asking the second value & how come char is stored in int form I took this from an example on web

#include <stdio.h>
// source tutorial points
int main(){
int c;
char d;
printf("Enter First value \n");
c = getchar();
printf("Enter Second value \n");
d = getchar();
printf("You have entered first \n");
putchar(c);
printf("You have entered second \n");
putchar(d);
return(0);
}
when I am entering first value it is not asking for other value please help I do not expect a character not possible in char.
Because each time you input a character and hit ENTER. So, second getchar in your code reads the enter character.
Your code should change to:
c = getchar();
getchar(); // for consuming the enter character
printf("Enter Second value \n");
d = getchar();
getchar(); // for consuming the enter character
The output:
Enter First value
a
Enter Second value
b
You have entered first
a
You have entered second
b

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

Unwanted multiple menu prints in a while loop program in C [duplicate]

This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 5 years ago.
C beginner here and I'm trying to learn to write a menu program. Below is my code
//A test file to test functions
#include <stdio.h>
#include <stdlib.h>
int enterChangeChar();
void printMenu();
char C = ' ';
int main()
{
char inputVal;
while (1)
{
printMenu();
scanf("%c", &inputVal);
switch (inputVal)
{
case 'c': enterChangeChar(); break;
case 'q': exit(0);
}
}
return 0;
}
int enterChangeChar()
{
int input;
printf("Would you like to Enter or Change the Character value?\n\n");
printf("Enter 1 to Assign OR 2 to Change the value of C: \n");
scanf("%d", &input); //input a integer value
if(input == 1)
{
printf("Enter a character: \n");
scanf(" %c", &C);
printf("You entered: %c", C);
}
else if (input == 2)
{
printf("Change Value option selected\n");
}
return 0;
}
void printMenu()
{
printf("Select a menu choice from the options below: \n\n");
printf(" OPTIONS INPUT\n");
printf("Enter/Change Character 'c'\n");
printf("Quit Program 'q'\n\n");
printf("Enter your CHOICE:\n");
}
when I run the program. The menu is printed twice after I input a character. Why is the program doing so?
Select a menu choice from the options below:
OPTIONS INPUT
Enter/Change Character 'c'
Quit Program 'q'
Enter your CHOICE:
c
Would you like to Enter or Change the Character value?
Enter 1 to Assign OR 2 to Change the value of C:
1
Enter a character:
v
You entered: v
Select a menu choice from the options below:
OPTIONS INPUT
Enter/Change Character 'c'
Quit Program 'q'
Enter your CHOICE:
Select a menu choice from the options below:
OPTIONS INPUT
Enter/Change Character 'c'
Quit Program 'q'
Enter your CHOICE:
q
EDIT: just added the printMenu() function code which I missed out earlier.
Edit 2: Maybe my question is not clear enough. The problem is not with getchar and scanf. The problem is that the menu prints twice after user inputs a character even though it's only called once in the whole program.
Edit 3: Final Edit: Guys I got it now. \n was in the input buffer and whenever choice was given, it was counted as input so the menu was printed multiple times. Thanks for the help.
There are unused newline characters '\n' in your input stream that need to be drained.
scanf() often causes confusion because it will leave the trailing '\n' in the input stream. In your case, the newline is getting picked up by the subsequent getchar().
int main()
{
while (1)
{
char inputVal;
printMenu();
do {
inputVal = getchar();
} while (inputVal == '\n');
switch (inputVal)
{
case 'c': enterChangeChar(); break;
case 'q': exit(0);
}
}
return 0;
}

I cannot seem to loop again after selecting default in switch case in C

hello guys I coded something like kfc menu,and I got it to work(finally),but when I input something other than numbers for "menu",eg:the letter "A", I just can't get it to loop again to normal,instead it finishes the program
#include <stdio.h>
#include <stdlib.h>
int main()
{
char counter='y';
float totalprice=0;
while (counter=='Y' || counter=='y')
{
int menu;
float price=0;
printf("\nplease select from menu:");
scanf (" %i", &menu);
switch(menu)
{
case 1: {
printf("\none hotbox1 =RM10.50");
totalprice=totalprice+10.50;
break;
}
case 2: {
printf ("\none hotbox2=RM10.60");
totalprice=totalprice+10.60;
break;
}
case 3:{
printf ("\none hotbox3=RM10.70");
totalprice=totalprice+10.70;
break;
}
default : {
printf ("\nplease enter proper number please:");
scanf("%2f", &menu);
break;
}
}
printf("\n\nadd order?(Y/N):");
scanf (" %c", &counter);
}
printf("\n\nThe total price is: %f", totalprice);
return 0;
}
You should use fgets() (reference here) first and then sscanf() (reference here), checking it's return value to see if it's a number.
char inputBuffer[MAX_BUFFER];
do
{
fgets(inputBuffer, MAX_BUFFER, stdin);
}
while(sscanf(inputBuffer, "%d", &menu) != 1)
You scanf with %f in the default case, I am fairly certain that is for floats. Use %d.
Remove scanf("%2f", &menu);
Switch in C does not support char in switch-case. Before you start switch-case validate the user input. If it is a number go into switch case otherwise display a user message to enter only numeric value
I recommend that you debug this by printing out the value of "counter" at various points in the loop (i.e. after you read it in, at the bottom of the loop, etc.). This will give you visibility into what your code is doing.
You can try something like this
#include <stdio.h>
int main()
{
char counter;
float totalprice=0;
int menu=0;
do
{
printf("\n1. one hotbox1=RM10.50");
printf("\n2. one hotbox2=RM10.60");
printf("\n3. one hotbox3=RM10.70");
printf("\nplease select from menu:");
scanf ("%d", &menu);
switch(menu)
{
case 1:
printf("\none hotbox1 =RM10.50");
totalprice=totalprice+10.50;
break;
case 2:
printf ("\none hotbox2=RM10.60");
totalprice=totalprice+10.60;
break;
case 3:
printf ("\none hotbox3=RM10.70");
totalprice=totalprice+10.70;
break;
default :
printf ("\nplease enter proper number please:");
scanf("%d", &menu);
}
printf("\n\nadd more order?(Y/N):");
fflush(stdin); //to empty the input stream.
scanf("%c",&counter);
}while(tolower(counter) != 'n'); //tolower returns the lowercase character.
printf("\n\nThe total price is: %.2f", totalprice);
return 0;
}
When scanf("%i", &menu) tries to read an integer from the input, it finds A, which it cannot interpret as a number, so it does not read it(*). Then the next scanf continues reading the input from when the other left off and happily reads the letter 'A'. Since you loop as long as the read letter is either 'y' or 'Y' (which A is neither), it exits the loop.
(*) read up on the documentation of scanf to see how to tell if it encountered an error.
Note: scanf("%i", &menu) should be scanf("%d", &menu) as%d` is the formatting symbol for integers.
One solution would be to change the loop condition to:
while (counter!='N' && counter!='n')
{
...
}
This way you end the loop only if an explicit 'N' or 'n' is inputted.
Note: it won't help if you accidentally type 'n' for the menu item, so see the comment about the error handling above.

Resources