C - Switch-case prints case twice - c

I have written the following switch-case:
char input;
int run = 1;
while(run){
printf("Would you like to update the student's name? Enter Y or N (Y=yes, N=no)\n");
input = getchar();
switch (input)
{
case 'N':
run = 0;
break;
case 'n':
run = 0;
break;
case 'Y':
printf("Please enter the updated name\n");
scanf("%s", st->name);
run = 0;
break;
case 'y':
printf("Please enter the updated name\n");
scanf("%s", st->name);
run = 0;
break;
case '\n':
break;
default:
printf("Wrong input. Please enter a valid input (Y or N)\n");
}
}
When I run it does this:
Please enter the id of the student that you would like to update
1
Would you like to update the student's name? Enter Y or N (Y=yes, N=no)
Would you like to update the student's name? Enter Y or N (Y=yes, N=no)
Why does it print the question twice? Can anyone help?
Other than that the cases run as expected.

The function getchar reads all characters including new line characters. Instead use
scanf( " %c", &input );
Also your switch statement has a duplicated code. Write for example
switch (input)
{
case 'N':
case 'n':
run = 0;
break;
case 'Y':
case 'y':
printf("Please enter the updated name\n");
scanf("%s", st->name);
run = 0;
break;
//...
The same approach you can use for other labels of the switch statement. and remove this code
case '\n':
break;

Related

How to prompt the user to loop in C?

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.

How Terminate the Program on Pressing Enter key in C?

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');

Im having a problem with a while loop and switch

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

Why will my program not flag characters?

I'm making this program using switch statements that will assign letter grades based on if the user enters numbers 0 - 10. If the user enters a number that is not 0-10, the program outputs an error message and has the user re-enter. However, if the user enters a character the program will loop at the default case. I want it to output the error message from the default case once, and have them re-enter if they enter a character. I'm not sure as to why it loops the default case when a character is entered though.
#include <stdio.h>
int main()
{
int grade;
int r;
while((r = scanf("%i", &grade)) != EOF)
{
switch(grade)
{
case 10:
case 9:
printf("Your grade is an A\n");
break;
case 8:
printf("Your grade is a B\n");
break;
case 7:
printf("Your grade is a C\n");
break;
case 6:
printf("Your grade is a D\n");
break;
case 5:
case 4:
case 3:
case 2:
case 1:
case 0:
printf("Your grade is an F\n");
break;
default:
printf("Invalid score, please re-enter\n");
}
}
return 0;
}
Try something like:
#include <stdio.h>
int main()
{
int grade;
int r=0;
while(r != 1)
{
scanf("%i", &grade);
switch(grade)
{
case 10:
case 9:
printf("Your grade is an A\n");
r=1
break;
case 8:
printf("Your grade is a B\n");
r=1
break;
case 7:
printf("Your grade is a C\n");
r=1
break;
case 6:
printf("Your grade is a D\n");
r=1
break;
case 5:
case 4:
case 3:
case 2:
case 1:
case 0:
printf("Your grade is an F\n");
r=1
break;
default:
printf("Invalid score, please re-enter\n");
break;
}
}
return 0;
}
This will clear the input buffer on an invalid input and allow a retry.
#include <stdio.h>
int main()
{
int grade;
int r;
while((r = scanf("%i", &grade)) != EOF)
{
if ( r != 1) {//r == 1 is successful input of integer
grade = -1;//reset grade on invalid input
}
switch(grade)
{
case 10:
case 9:
printf("Your grade is an A\n");
break;
case 8:
printf("Your grade is a B\n");
break;
case 7:
printf("Your grade is a C\n");
break;
case 6:
printf("Your grade is a D\n");
break;
case 5:
case 4:
case 3:
case 2:
case 1:
case 0:
printf("Your grade is an F\n");
break;
default:
printf("Invalid score, please re-enter\n");
while ( getchar() != '\n');//clear input buffer
}
}
return 0;
}
The reason your code always loops is because there is no way to exit out of your while other than to kill the program. Remember that break only breaks out of the inner-most switch or loop.
The cleanest way to break out of multiple levels is to use a flag. One way to do what you want is like this:
bool valid_grade = false;
while(!valid_grade && (r = scanf("%i", &grade)) != EOF)
{
valid_grade = true;
switch(grade)
{
case 10:
// unchanged from your code
default:
valid_grade = false;
printf("Invalid score, please re-enter\n");
}
}

C programming do while with switch case program

I have been able to do switch case program but I want program to run again and again until a user selects to quit.
I basically wants program to run again and again using do while loop...
switch(I)
{
case 1:
printf("67");
break;
case 2:
printf("45");
break;
default:
printf("default");
}
Use a do...while loop like this:
int I = 1; //Initialize to some non-zero number to prevent UB
printf("Enter 0 to quit \n");
do{
if (scanf("%d",&I) != 1) //If invalid data such as characters are inputted
{
scanf("%*[^\n]");
scanf("%*c"); //Clear the stdin
}
} while(I!=0); //Loop until `I` is not 0
This piece of code will loop until the user enters 0. You can change this code according to your needs. If you want your switch in this, copy your posted code after the scanf.
The loop will run until you enter -1 as input.
#include<stdio.h>
int main()
{
int I;
do
{
puts("Enter -1 to quit");
printf("Enter your choice: ");
scanf("%d",&I);
switch(I)
{
case 1:
printf("67\n");
break;
case 2:
printf("45\n");
break;
case -1:
puts("Bye");
break;
default:
printf("default\n");
}
}while(I != -1);
return 0;
}
this program runs untill user gives input 0 or a negative number...
#include<stdio.h>
int main()
{
int I;
do
{
scanf("%d",&I);
switch(I)
{
case 1:
printf("67");
break;
case 2:
printf("45");
break;
default:
printf("default");
}
}
while(I>0);
return 0;
}
Simple Use of Do-While Loop.
Choice is the variable in which user's choice will be stored, whether he wants to print the statement again or not.
int choice;
do{
printf("\nHello World!"); //This is the task of the program (Replace it with your task)
printf("\nDo You Want to Print it again ? 1 Yes/0 No: ");
scanf("%d",&choice);
}while(choice==1); //Loop will exit when choice gets value other than 1
// here switch will run until A is not equal to S
int N;
char A;
do{
cin>>N;
N = N%7;
cout<<endl;
cin>>A;
switch(N)
{
case 1: cout<<"Monday"<<endl; break;
case 2: cout<<"Tuesday"<<endl; break;
case 3: cout<<"Wednesday"<<endl; break;
case 4: cout<<"Thursday"<<endl; break;
case 5: cout<<"Friday"<<endl; break;
case 6: cout<<"Saturaday"<<endl; break;
case 0: cout<<"Sunday"<<endl; break;
default: cout<<"Invalid Input"; }}
while(A!='S');

Resources