I want to delete the contents of an int variable when it gets to an else statement.
The program requests a number between 1 and 5 using scanf and the number is stored in the int variable and if the number isn't between 1 and 5 then the user is directed to an else statement and I have used a goto statement to take it back to the start and I was wondering how I removed the contents of the variable during the else statement so I don't create a continuos loop.
With getchar it's fpurge(stdin). I'm running Mac OS X.
BELOW IS THE CODE:
#include <stdio.h>
int main (int argc, const char * argv[])
{
int code;
start:
puts("Please type your error code.");
puts("Range 1-5: ");
scanf("%d", &code);
switch(code)
{
case 1:
printf("INFORMATION\n");
case 2:
printf("INFORMATION\n");
case 3:
printf("INFORMATION\n");
case 4:
printf("INFORMATION\n");
case 5:
printf("INFORMATION\n");
default:
printf("INFORMATION\n");
goto start;
}
}
Just set the int value to something else, eg:
theValue = 0;
You are probably looking for a do...while loop
Edit Don't forget your break statements!!
do
{
puts("Please type your error code.");
puts("Range 1-5: ");
scanf("%d", &code);
switch(code)
{
case 1:
printf("INFORMATION\n");
break;
case 2:
printf("INFORMATION\n");
break;
case 3:
printf("INFORMATION\n");
break;
case 4:
printf("INFORMATION\n");
break;
case 5:
printf("INFORMATION\n");
break;
default:
printf("INVALID CODE\n");break;
}
} while(code<1 || code> 5);
Related
When I enter the letter 'q' as grade, it runs infinitely.
#include <stdio.h>
#include <stdbool.h>
int main(void) {
int grade;
bool flag = true;
while (flag) {
puts("-----------------------------"); // comment
printf("What's your grade out of 10? ");
scanf(" %d", &grade);
switch (grade) {
case 10:
case 9:
case 8:
case 7:
case 6:
printf("Pass\n");
break;
case 5:
printf("Fail\n");
break;
case 4:
printf("Fail\n");
break;
case 3:
printf("Fail\n");
break;
case 2:
printf("Fail\n");
break;
case 1:
printf("Fail\n");
break;
case 0:
printf("Fail\n");
break;
default:
printf("Illegal Grade\n");
flag = false;
break;
}
}
return 0;
}
scanf(" %d",&grade);
It scans int in string. "q" is not int. When you enter "q", value of the variable grade left unchanged. You must check returned value of scanf to validate number of filled placeholders.
if (scanf(" %d",&grade) != 1) {
printf("Illegal Grade\n");
exit(1); // or break
}
Other parts are ok.
scanf(" %d", &grade); fails when you type something that cannot be parsed as into an integer. grade is not modified, so it is uninitialized if the conversion error happens immediately and the behavior is undefined, otherwise you get the same value and behavior as the previous time.
The offending input stays in the input stream, so the same thing happens when the code executes again in the while loop, hence the infinite loop.
You want to test if the conversion was successful and discard the input if not:
#include <stdio.h>
#include <stdbool.h>
int main(void) {
int res, c, grade;
bool flag = true;
while (flag) {
puts("-----------------------------"); // comment
printf("What's your grade out of 10? ");
res = scanf("%d", &grade);
if (res == EOF)
break;
if (res == 0) {
printf("Invalid input\n");
/* discard the offending line of input */
while ((c = getchar()) != EOF && c != '\n')
continue;
/* try again */
continue;
}
switch (grade) {
case 10:
case 9:
case 8:
case 7:
case 6:
printf("Pass\n");
break;
case 5:
case 4:
case 3:
case 2:
case 1:
case 0:
printf("Fail\n");
break;
default:
printf("Illegal Grade\n");
flag = false;
break;
}
}
return 0;
}
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");
}
}
Could someone help me with my code?
My program isn't terminating. After choosing a brand, it should terminate but it loops forever.
#include<stdio.h>
int main (void)
{
int number,count=0 ;
while (count<3)
{
printf("Menu:\n");
printf("1.Proace\n");
printf("2.Yonex\n");
printf("3.Reebook\n");
printf("0.Exit\n");
printf("Enter your selection:");
scanf("%d",&number);
switch (number)
{
case 0:
printf("exit.\n");
break;
case 1:
printf("You have selected proace.\n");
break;
case 2:
printf("You have selected yonex.\n");
break;
case 3:
printf("You have selected reebook.\n");
break;
default:
printf("Please try again.\n");
exit(0);
}
}
return 0;
}
I guess you are misunderstanding the default case of switch: it is executed only if number is not 0,1,2,3.
If you want to exit each time a exit(0) for each case 0 1 2 3
#include<stdio.h>
int main (void)
{
int number,count=0 ;
while (count<3)
{
printf("Menu:\n");
printf("1.Proace\n");
printf("2.Yonex\n");
printf("3.Reebook\n");
printf("0.Exit\n");
printf("Enter your selection:");
scanf("%d",&number);
switch (number)
{
case 0:
printf("exit.\n");
exit(0);
break;
case 1:
printf("You have selected proace.\n");
exit(0);
break;
case 2:
printf("You have selected yonex.\n");
exit(0);
break;
case 3:
printf("You have selected reebook.\n");
exit(0);
break;
default:
printf("Please try again.\n");
}
}
return 0;
}
BTW a better code should be
#include<stdio.h>
int main (void)
{
int number;
bool canExit = false;
while (canExit == false)
{
canExit = true;
printf("Menu:\n");
printf("1.Proace\n");
printf("2.Yonex\n");
printf("3.Reebook\n");
printf("0.Exit\n");
printf("Enter your selection:");
scanf("%d",&number);
switch (number)
{
case 0:
printf("exit.\n");
break;
case 1:
printf("You have selected proace.\n");
break;
case 2:
printf("You have selected yonex.\n");
break;
case 3:
printf("You have selected reebook.\n");
break;
default:
printf("Please try again.\n");
canExit = false;
}
}
return 0;
}
Replace while (count<3) with a boolean, bool loop=true; followed by while (loop). And then inside the switch when you wish to exit, don't call the exit function but simply set loop=false;.
Your break in the switch() exits the switch() but does not exit the while().
If you enter 0, default: case won't be executed.
Is it really what you wanted ?
int number=4 ;
while (number > 3)
and you can delete count, which I can't see is being used anywhere
Actually, the following structure might be better, since you won't have to put an arbitrary number in the comparison:
int number;
do {
// the thing
} while(number > 3);
In this case, it determines whether to continue the loop AFTER the first execution rather than before it. So in a do-while it will ALWAYS execute the do ONCE before the condition can break it, even if the condition is false to begin with!
I would replace your switch with:
char* brand[] = { "proace", "yonex", "reebook" };
do{
if(number == 0)
printf("exit.\n");
else if(number <= 3)
printf("You have selected %s.\n", brand[number]);
else
printf("Please try again");
}while(number > 3);
Encapsulate it in do-while loop with condition number > 3 and it will loop until user select 0-3. In this case, exit(0) is unnecessary.
You are not updating the count variable that is why it is not exiting. For exiting the while loop the count should be greater than or equal to 3.
As long as you will be giving the input 0, 1, 2 or 3 you will never reach default which has exit() and thus the program will continue to run as we have set while conditional as (count < 3) i.e. 0 < 3 which is always true. So no chance of exiting the program by while conditional. The only chance to terminate the program is from default.
So if you give input anything other than 0, 1, 2 or 3, you will reach default which will call exit() and thus will cause the program to terminate.
Hello you can exit your program by including the header file #include in your header file section.
Then you can use the exit() command
Eg :-
#inlcude<process.h>
#include<studio.h>
into opt;
printf(" enter o ");
scant(" %d",&opt);
switch(opt)
case 0: printf(" exiting the program");
getch();
exit();
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');
I'm building a program using a grade report and I'm having trouble calculating my GPA using a switch case. I'm unsure why it isn't assigning the correct values. I would also like if there is a way to ask for the number of classes taken and then get the loop to perform that said number of times.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Grades
{
char Name[20];
int Hrs;
int ID;
char ClassName[20];
char Grade;
char ClassID[6];
};
int main ()
{
struct Grades Transcript[6];
int classCnt = 0;
int vHrs=0, vGPA=0, totalHours=0, totalPoints = 0;
char vGrade;
char vName[20], vCID[6], vClassName[20];
printf("Enter Students Name: ");
fgets(vName, 20, stdin);
do
{ printf("\nEnter Class ID: ");
fgets(vCID, 6, stdin);
fflush(stdin);
strcpy_s(Transcript[classCnt].ClassID, vCID);
printf("Enter Class Name: ");
fgets(vClassName, 20, stdin);
strcpy_s(Transcript[classCnt].ClassName, vClassName);
printf("Enter Class Hours: ");
fflush(stdin);
scanf("%d", &vHrs);
Transcript[classCnt].Hrs = vHrs;
printf("Enter Class Grade: ");
fflush(stdin);
scanf("%c", &vGrade);
Transcript[classCnt].Grade = vGrade;
classCnt++;
fflush(stdin);
totalHours+=vHrs;
switch (vGrade) {
case 'A':
case 'a': 4*vHrs;
break;
case 'B':
case 'b': 3*vHrs;
break;
case 'C':
case 'c': 2*vHrs;
break;
case 'D':
case 'd': 1*vHrs;
break;
case 'F':
case 'f': 0;
break;
default: printf("Invalid Grade");}
totalPoints += vGrade;
vGPA = (totalPoints/totalHours);
}while(classCnt<=5);
printf("********************************** Grade Report: *************************************");
printf("\n%d\n", totalHours);
printf("%d\n", vGPA);
system("Pause");
return 0;
The expression statement:
4*vHrs;
is certainly valid in C but it doesn't actually do anything (a).
Perhaps you may want to assign it to something, such as with:
addPoints = 4 * vHrs;
(declaring addPoints beforehand, of course) and then use that to affect totalPoints later:
totalPoints += addPoints;
In terms of asking for a class count, you can use scanf("%d",...) to get an integer from the user and then just use that integer in a loop:
#include <stdio.h>
int main (void) {
int num, count;
printf ("Enter countdown value: ");
scanf ("%d", &count);
for (num = count; num > 0; num--)
printf ("%d ", num);
puts ("BLAST OFF");
return 0;
}
A sample run being:
Enter countdown value: 10
10 9 8 7 6 5 4 3 2 1 BLAST OFF
(a) Even a statement like 42; is valid, though useless. The reason this is allowed is because you can have side effects in expressions. The classic case, though not many learners immediately see this, is the venerable i++;.
This is an expression which gives you the current value of i (which you throw away unless you're using it somehow), then increments i as a side effect.
case 'A':
case 'a': 4*vHrs;
break;
case 'B':
case 'b': 3*vHrs;
break;
case 'C':
case 'c': 2*vHrs;
break;
case 'D':
case 'd': 1*vHrs;
break;
case 'F':
case 'f': 0;
None of these lines have any effect on the program you've written. You might want to assign 3*vHrs, 4*vHrs etc to a variable and then do the calculations below. You probably meant vHrs *= 3 or vHrs *=4 or something like that?