I am working on a project, where you answer a char, and if it is not one of the 4 answers, it tells you to try again. If it is not the correct one of the 4, it stops running. Here is a snippit.
#include <stdio.h>
#include <stdbool.h>
bool switchCheck = true;
char answer;
printf("A. English\nB. French\nC. Spanish\nD. German\n");
do{
scanf("%c\n", &answer);
switch (answer){
case 'C':
printf("Very nice ");
break;
case 'B':
case 'A':
case 'D':
printf("Sorry! Incorrect. Code Ends\n");
switchCheck =false;
break;
default:
printf("Try Again\n");
}
}while(switchCheck==true);
For some reason, when I input A, B, or D, it first prints the result for default, and if I do it again immediately afterward, it gives me the right input. Any help?
Thanks!
You are using scanf like
scanf("%c\n", &answer);
Instead use
scanf( " %c", &answer );
See the blank before the conversion specifier %c. It allows to skip white spaces.
Related
The code is supposed to check for a vowel input. If found, it would print "Vowel" and if there is none it should print "consonent". But the compiler is going to the default case regardless of the input and I can't find where the mistake is. Please Help.
Here's my code:
#include<stdio.h>
void main()
{
char ch;
printf("Insert a Char \n");
scanf("%d", &ch);
switch(ch)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
printf("Vowel");
break;
default:
printf("Consonent");
}
}
The conversion specifier %d in this call
scanf("%d", &ch);
is invalid. It tries to read a number. So entering a letter like 'A' results in input error.
The compiler can issue a warning or even an error reporting that for example
format ‘%d’ expects argument of type ‘int *’, but argument 2 has type
‘char *’
Because using an invalid format can result in undefined behavior.
Here is a demonstrative program
#include <stdio.h>
int main(void)
{
char s[] = "ABCD";
puts( s );
scanf( "%d", ( int * )s );
puts( s );
return 0;
}
If for example even to enter a valid ASCII code as for example 65 of the letter 'A' then the program output might look like
ABCD
A
That is the memory occupied by the array was overwritten.
Instead use the following call.(if you want to skip white spaces)
scanf( " %c", &ch );
or the following call
scanf( "%c", &ch );
Pay attention to that according to the C Standard the function main without parameters shall be declared like
int main( void )
First thing %d accepts an integer, not a character so correct this and run then place break after each case ends if you don't place break it will run all case till the end which is the default.
Example:-
char ch;
printf("Insert a Char \n");
scanf("%c", &ch);
switch(ch)
{
case 'a':printf("Vowel");
break;
case 'e':printf("Vowel");
break;
case 'i':printf("Vowel");
break;
case 'o':printf("Vowel");
break;
case 'u':
printf("Vowel");
break;
default:
printf("Consonent");
}
Hope it will help.
Happy coding :-)
you should use "%c" as the format. when you use "%d", the value is 0 (because no integers have been detected in the input string). Refer to https://en.cppreference.com/w/c/io/fscanf#Example.
This issue, and void main() instead of int main(), should produce a compiler warning.
Thanks Everyone. I appreciate the help!
I should have noticed the data type though.
include
void main()
{
char ch;
printf("Insert a Char \n");
scanf("%c", &ch);
switch(ch)
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
printf("Vowel");
break;
default:
printf("Consonant");
}
}
Here is a minimal form of the code emphasizing the issue I have.
Code fails at "exit"(case '0') - program simply crashes. I suspect it is related to the while loop.
The issue occurs no matter what character i choose for the exit case (instead of '0').
#include <stdio.h>
void main()
{
int run=1;
char menu_option;
while (run==1)
{
printf("Choose case:\n");
scanf ("%s", &menu_option);
switch (menu_option) {
case '1':
printf("1");
break;
case '2':
printf("2");
break;
case '0':
run=0;
break;
default:
printf("Wrong input, try again\n");
}
}
}
menu_option is not a string, so %s is the wrong format specifier. You need %c, prefixed with a space to prevent whitespace (including newline) being interpreted as valid character input.
scanf (" %c", &menu_option);
I am trying to teach myself C. For fun and for my own development, I have created a code that prompts the user for a letter grade, then outputs the range of that letter grade. Here is what I have so far:
//Ted C. Lim
#include "stdio.h"
int main()
{
char grade;
printf("Enter a single character grade: ");
scanf("%c", &grade);
printf("You entered %c as the grade. ", grade);
switch(grade)
{
case 'A':
printf("The grade range for A and A- is 100%% - 90%%.");
break;
case 'B':
printf("The grade range for B and B- is 80%% - 89%%.");
break;
case 'C':
printf("The grade range for C and C- is 70%% - 79%%.");
break;
case 'D':
printf("The grade range for D and D- is 60%% - 69%%.");
case 'F':
printf("The grade range for F is 0%% - 59%%.");
default:
printf("That grade does not exist.");
break;
}
}
If you run the program, you will see that it asks the user only once, returns the proper output, then stops. What I would like to do is repeat the prompt indefinitely until the user inputs something like 'Q' to quit. I know I should use some sort of loop here, but I'm not quite sure how to apply it.
There a couple different options you could choose here, both the while and the do while loop would work. Personally, I would say that a do while loop would be better fit for this case, mostly because you know for sure that you want the program to prompt the user at least once. In order to use it you would need to place the do before the printf statements and then run while some scanf input at the end is != "Q"
You can use a while loop, along with another character case to exit out of the loop.
char grade;
while (1)
{
printf("Enter a single character grade (or 'X' to exit): ");
scanf(" %c", &grade);
printf("You entered %c as the grade. ", grade);
if (grade == 'X') // Or another letter, make it clear what you're using
{
break;
}
// Output code here...
}
I would also recommend you check for both lowercase and uppercase letters. In the switch statement:
case 'A':
case 'a':
printf("The grade range for A and A- is 100%% - 90%%.");
break;
In the if statement:
if (grade == 'X' || grade == 'x')
{
break;
}
To repeat an action indefinitely, you could wrap it inside a while loop with a condition that is always true (e.g., while (1) { ... }) as follows:
#include <stdio.h>
#include <ctype.h>
int main()
{
char grade;
while (1)
{
printf("Enter a single character grade (or Q to quit):\n");
scanf(" %c", &grade);
grade = toupper(grade);
if (grade == 'Q') break;
printf("You entered %c as the grade.\n", grade);
switch(grade)
{
case 'A':
printf("The grade range for A and A- is 100%% - 90%%.\n");
break;
case 'B':
printf("The grade range for B and B- is 80%% - 89%%.\n");
break;
case 'C':
printf("The grade range for C and C- is 70%% - 79%%.\n");
break;
case 'D':
printf("The grade range for D and D- is 60%% - 69%%.\n");
break;
case 'F':
printf("The grade range for F is 0%% - 59%%.\n");
break;
default:
printf("That grade does not exist.\n");
break;
}
}
return 0;
}
You'll notice I've made a few other modifications, which I'll run through here:
include "stdio.h" should really be #include <stdio.h>. The angle brackets tell the compiler to look in the standard directory for system header files.
I also added #include <ctype.h> because I'm using the toupper() function to convert the input character to upper case. This makes your code easier to use, because it will now accept both upper and lower case letters.
The scanf() format string includes a space before %c. This will skip over any white space characters including newline characters. Without it, the program would treat these characters as actual inputs and tell you that the \n grade does not exist.
The break statement can be used to exit the loop when the user enters Q. There were also a couple of breaks missing from your switch block.
The main() function is declared as int main() { ... }, so it should return an integer value. If no errors have occurred, this value should be zero.
Encase your switch case inside of a while loop that is true and it will run indefinitely. You can also use scanf to check for a specific key to be entered to stop it too.
I am writing a piece of code and in one part of my code I am using a switch statement in C language. if I press n it exits correctly if I press y it will infinite loop the default statement until I press control c. what am I doing wrong here. been changing the while statement but can't find the right one.
int main()
{
char ans;
printf("DO you want to continue?");
scanf("%c", &ans);
do
{
switch(ans)
{
case 'y':
some stuff...
printf("DO you want to continue?");
scanf("%c", &ans);
break;
case'n':
printf("BYE");
break;
default:
printf("error, you must enter y or n");
continue;
}
}
while (ans!='n');
return 0;
}
When you press enter, the linefeed character \n is added to the input stream. Your code does not anticipate this, because switch(ans) only handles y, n or “everything else” (which includes the linefeed character).
To fix this, allow scanf to ignore any preceding whitespace by changing your format string to " %c" instead, e.g.
scanf(" %c", &ans);
// ^ space character inserted here
I think it would make more sense to move the scanf call to inside the loop, like this:
int main()
{
char ans;
do
{
printf("DO you want to continue?");
if (scanf(" %c", &ans) != 1)
break;
switch(ans)
{
case 'y':
// some stuff...
break;
case 'n':
printf("BYE");
break;
default:
printf("error, you must enter y or n");
continue;
}
}
while (ans!='n');
}
Don't forget to always check the result of scanf(). It will return the number of items successfully scanned (in your case, you want it to return 1). If it returns 0 or a negative number, then another problem has occurred.
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.