This question already has answers here:
abnormal behavior of scanf [duplicate]
(3 answers)
Closed 3 years ago.
I´m trying to make a program that tells you if a letter is a vowel o consonant and then ask the user if he/she wants to use the program again.
Using just the switch statement works totally fine. My problem comes when inserting the do-while loop. On the first try, the program works smoothly, but in the second and following loops, after asking the user if he wants to try again by typing 1, the program "jumps" the part where the user writes its input (scanf("%c", &letter)) and executes the rest of the program considering the previously typed 1 as the input and messing up everything.
I´ve tried looking for the answer on similar questions and videos, but I´m quite new and I just can´t grasp it. I have another program with a similar problem. I will really appreciate your help :)
int main()
{
char letter;
int new_try;
do {
printf("Is you letter a vocal or a consonant?\n");
printf ("\nPlease submit a letter:\n");
scanf("%c", &letter);
switch(letter) {
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
printf("This letter is a vowel\n");
break;
default : printf("This letter is a consonant\n");
break;
}
printf("Do you wish to try again?\n [1.Yes 2. No]\n");
scanf("%d", &new_try);
}
while(new_try != 2);
return 0;
}
You need to clean the input buffer. Otherwise, as long as there are characters in your input buffer, the program will not wait for new input from user. Here is the solution.
#include <stdio.h>
int main() {
char letter;
int new_try;
do{
printf("Is you letter a vocal or a consonant?\n");
printf ("\nPlease submit a letter:\n");
scanf("%c", &letter);
while ((getchar()) != '\n');
switch(letter) {
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U': printf("This letter is a vowel\n");
break;
default : printf("This letter is a consonant\n");
break;
}
printf("Do you wish to try again?\n [1.Yes 2. No]\n");
scanf("%d", &new_try);
}while(new_try != 2);
return 0;
}
Update
As #David C. Rankin mentioned, using scanf(" %c", &letter); can also addresss your issue. However, it doesn't address a matching failure. In the above case, you also need to validate the input.
Related
I’m new to C and currently doing a Jack ‘N Poy that requires the project to restart when the user prompt it like by answering y. However, I can’t seem to grasp its pattern. Have tried it on C++ and it worked but not on C. Can anyone help? I want the user to have the ability to play again after finishing the game.
Here is the code:
#include<stdio.h>
int main (){
char firstPlayer, secondPlayer, again;
do{
printf("Jack 'n Poy)\nEnter Player 1 input: ");
scanf("%c ", &firstPlayer);
printf("Enter Player 2 input: ");
scanf("%c", &secondPlayer);
switch (firstPlayer){
case 'x':
switch (secondPlayer){
case 'x':
printf("Draw");
break;
case 's':
printf("Player 2 wins");
break;
case 'p':
printf("Player 1 wins");
}
break;
case 's':
switch (secondPlayer){
case 'x':
printf("Player 1 wins");
break;
case 's':
printf("Draw");
break;
case 'p':
printf("Player 2 wins");
}
break;
case 'p':
switch (secondPlayer){
case 'x':
printf("Player 2 wins");
break;
case 's':
printf("Player 1 wins");
break;
case 'p':
printf("Draw");
}
break;
default:
printf("Invalid input");
}
printf("\nPlay again? (y/n)");
scanf("%c", &again);
}
while (again == 'y');
printf("Thank you for playing");
return 0;
}
Have also tried adding a substitute variable for the y and yes it does loop, but the loop skips the first question.
Your help are very much appreciated. Thank you very much!
You need to change the format to:
scanf(" %c", ...);
in all scanfs. Note the ' ' before %c
Your again is a string. You can use strcmp(expectedString,inputString) as the condition at while. You will need to include the string.h header file to be able to do this.
Alternatively, change again to char type, i.e. char again;
And then use %c in the last scanf, i.e. scanf("%c", &again);. You may face skipped character scenario if spaces or newlines are entered. In that case, refer to this answer for guidance.
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.
i am making a small project in which I have to convert different values to different bases like 10,8,16.But the problem is that I want to run the program till the user press 6 but if user hit Enter key then too it is waiting for the input rather than simply terminating. I'm using C11 version of C on online compiler.
and here's my code.
#include "ConvertInBackgnd"
#include<stdio.h>
int main() {
int choice;
printf("1 for Decimal to Binary\n2 for Binary to Decimal\n3 for Decimal to Octal\n4 for Octal to Decimal\n5 for Decimal to Hexadecimal \n6 for reconverting values \n");
l1: printf("Input your choice : ");
scanf("%d", &choice);
switch (choice) {
case 1:
dec_bin();
break;
case 2:
bin_dec();
break;
case 3:
dec_octal();
break;
case 4:
octal_dec();
break;
case 5:
dec_hex();
break;
case 6:
goto l1;
default:
printf("Invalid choice.");
break;
}
printf("Input 6 for reconverting the values.");
scanf("%d", &choice);
if (choice == 6) {
goto l1;
} else
return 0;
return 0;
}
I have made a separate file in which I have made functions and I thought it isnot necessary to put that code here too.
Consider using fgets to take input into a character array.
If needed, the input can be parsed with sscanf, strtol or others.
#include<stdio.h>
int main() {
char line[100] = "";
do {
printf("1 for Decimal to Binary\n2 for Binary to Decimal\n3 for Decimal to Octal\n4 for Octal to Decimal\n5 for Decimal to Hexadecimal \n6 for reconverting values \n");
printf("Input your choice : ");
fgets ( line, sizeof line, stdin);
switch ( line[0]) {
case '1':
printf ( "dec_bin()\n");
break;
case '2':
printf ( "bin_dec()\n");
break;
case '3':
printf ( "dec_octal()\n");
break;
case '4':
printf ( "octal_dec()\n");
break;
case '5':
printf ( "dec_hex()\n");
break;
case '6':
case '\n':
break;
default:
printf("Invalid choice.");
break;
}
if ( line[0] != '\n') {
printf("Input 6 for reconverting the values.");
fgets ( line, sizeof line, stdin);
}
} while ( line[0] == '6');
return 0;
}
To solve the enter problem:
scanf("%d", &choice)
Right now you are taking int value, try with char value and match the enter key with it. Then you'll be able to do what you are trying to do.
Ok, So I wanted to terminate the program if Enter key is pressed. So I was first a newbie then I realized that itsnot a big deal and to do so I just need to take a char as Input and then check that if that char input is enter key or not.
Its a sample code to terminate the program after pressing enter key.
char line;
scanf("%c",&line);
if(line=='\n')
return 0;
else
// your other code
But if your program doesnot take input then you should clear the buffer before the above provided code by adding just this single line before the above code.
while(getchar()!='\n');
while(Game == 0)
{
gotoxy(100,40);
setForeColor(MY_COLOR_WHITE);
printf("A- Jogar uma partida de Anabi\n");
gotoxy(100,42);
printf("B- Carregar partida anterior\n");
gotoxy(100,44);
printf("C- Descri%c%co do jogo\n", 135, 198);
gotoxy(100,46);
printf("D- Sair do jogo\n");
scanf("%c", &choice);
switch(choice)
{
//This part of the code should break my loop
case 'A':
case 'a':
gotoxy(100, 52);
printf("Please enter your name bellow\n");
gotoxy(98, 53);
printf("->");
scanf("%s",NamePlayer);
Game = 1;
break;
case 'B':
case 'b':
// in here I am going to call a function, the function that reads the file previously saved
//also here I am going to know if there is any saved files, and give an output to the user
break;
case 'C':
case 'c':
//This gets me to the description of the game, rules, etc.. and its working fine with the loop
DescricaoDoJogo();
break;
case 'D':
case 'd':
exit(0);
break;
default:
//This default is giving me trouble, should I use and If, else? Because when i choose the option C, and I get back to the menu what is inside the default executes
printf("Wrong choice.. Try again.. A, B, C or D..");
scanf(" %c", &choice);
system("cls");
break;
}
}
How is the calculation in the following program done in switch case? Why is the last case evaluated in this code?
I am new to learn C language and I can't get exact defination.
C code:
#incluse<stdio.h>
int main()
{
int ch ='a'+'b';
switch(ch)
{
case 'a':
case 'b':
printf("you enterd b\n");
case 'A':
printf("a as in ashar\n");
case 'b'+'a':
printf("you enterd a and b\n");
}
getch();
return 0;
}
I think you forgot to use of break in switch case :
switch(ch)
{
case 'a':
// some expressions
break;
case 'b':
printf("you enterd b\n");
break;
case 'A':
printf("a as in ashar\n");
break;
case 'b'+'a':
printf("you enterd a and b\n");
break;
}
The reason is when the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached. Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.
Please visit this page
In your program int ch = 'a' + 'b' is the same case 'b'+'a':, so the printf("you enterd a and b\n"); expression will be result.
you can Try online
In your code, switch(ch) causes control to jump to the case label whose expression matches the value of ch (if there is one). Since ch has the value 'a'+'b', and 'a'+'b' equals 'b'+'a', control jumps to the case 'b'+'a'.
Incidentally, when one wants each section of code in a switch statement to be separate, one must put a break; statement at the end of each section (or some other jump statement), as in:
switch (ch)
{
case 'a':
case 'b':
printf("You entered a or b.\n");
break;
case 'A':
printf("A as in ashar.\n");
break;
case 'b'+'a':
printf("You entered a and b.\n");
break;
}
Also note that you will not obtain the value 'a'+'b' when a user enters the characters “a“ and “b”. In C, 'a'+'b' is the sum of the numerical code for the character a and the numerical code for the character b. It is not a string concatenation of the two characters.
Switch case works like this, if ch == 'a' then case 1 will get executed else if ch == 'b' case 2 will get executed and so on. After each case break statement is kept to stop the overflow in between cases.