In the code below, if the user enters 1 or 2, everything proceeds smoothly.
But if I enter anything else besides 1 or 2, the loop runs, but an additional is required to continue the loop.
How do I eliminate the need for this ?
#include <stdio.h>
#include <ctype.h>
#include <math.h>
void clearKeyboardBuffer() {
int ch;
while ((ch = getchar() != '\n') && (ch != EOF));
}
void entry1(){
char chArr[BUFSIZ];
char choice, ch;
int choiceint, rating;
do{
printf("1.\tZoo\n2.\tMall\n3.\tExit\n\n");
printf("Choose a place by entering its numerical value: ");
fgets(chArr,sizeof(chArr),stdin);
sscanf(chArr, " %c", &choice);
// converts scanned char to int
choiceint = choice - '0';
if(!isdigit(choice) || choiceint > 3){
printf("You did not enter an accepted digit.\n");
}
else if(choiceint != 3){
switch(choiceint){
case 1:
printf("You chose the Zoo.\n");
printf("your rating : ");
scanf("%d", &rating);
break;
case 2:
printf("You chose the Mall.\n");
printf("your rating : ");
scanf("%d", &rating);
break;
}// end of switch
}// end of else if
else{
}// end of else
clearKeyboardBuffer();
}// end of do
while(choiceint !=3);
}
just move the call to clearKeyboardBuffer() right after //end of switch as in
char chArr[BUFSIZ];
char choice, ch;
int choiceint, rating;
do{
printf("1.\tZoo\n2.\tMall\n3.\tExit\n\n");
printf("Choose a place by entering its numerical value: ");
fgets(chArr,sizeof(chArr),stdin);
sscanf(chArr, " %c", &choice);
// converts scanned char to int
choiceint = choice - '0';
if(!isdigit(choice) || choiceint > 3){
printf("You did not enter an accepted digit.\n");
}
else if(choiceint != 3){
switch(choiceint){
case 1:
printf("You chose the Zoo.\n");
printf("your rating : ");
scanf("%d", &rating);
break;
case 2:
printf("You chose the Mall.\n");
printf("your rating : ");
scanf("%d", &rating);
break;
}// end of switch
clearKeyboardBuffer();
}// end of else if
else{
}// end of else
}// end of do
while(choiceint !=3);
You've got a problem with your if else loop. If the choice is not a digit or >3 you want to re-ask the user
#include <stdio.h>
#include <ctype.h>
#include <math.h>
void clearKeyboardBuffer() {
int ch;
while ((ch = getchar() != '\n') && (ch != EOF));
}
void entry1(){
char chArr[BUFSIZ];
char choice, ch;
int choiceint, rating;
do{
printf("1.\tZoo\n2.\tMall\n3.\tExit\n\n");
printf("Choose a place by entering its numerical value: ");
fgets(chArr,sizeof(chArr),stdin);
sscanf(chArr, " %c", &choice);
// converts scanned char to int
choiceint = choice - '0';
if(!isdigit(choice) || choiceint < 1 || choiceint > 3){
printf("You did not enter an accepted digit.\n");
}
// If 0 > choice > 3
else {
switch(choiceint){
case 1:
printf("You chose the Zoo.\n");
printf("your rating : ");
scanf("%d", &rating);
break;
case 2:
printf("You chose the Mall.\n");
printf("your rating : ");
scanf("%d", &rating);
break;
case 3:
break;
default:
break;
}// end of switch
}// end of else
clearKeyboardBuffer();
}// end of do
while(choiceint !=3);
}
Related
I am trying to create a program that assigns the user one of three questions at random. I figured out that part however I want to make it so that after they correctly answer their assigned question that they are asked if they want to take another one.
int main(void) {
srand(time(0));
int luckyNumber;
int quizNumber;
int score;
int totalScore;
int averageScore;
int attempts;
char answer1;
char answer2;
char answer3;
char opt1;
char loop = 'y';
printf("Welcome to the quiz program!\n");
while(loop == 'y') {
printf("Please enter a lucky number between 1 and 9: ");
scanf("%d", &luckyNumber);
quizNumber = rand() % 3 + 1;
printf("Your quiz number is %d\n", quizNumber);
if (quizNumber == quizNumber) {
while (score != 5) {
printf("Quiz 1\n");
printf("A. True\n");
printf("B. False\n");
printf("Enter your answer: ");
scanf(" %c", &answer1);
if (answer1 == 'B' || answer1 == 'b') {
printf("Correct!\n");
score = score + 5;
break;
}
else {
printf("Incorrect!, Try again.\n");
printf("\n");
}
break;
}
break;
}
printf("Would you like to go again y/n?");
scanf("%c", &loop);
if (loop != 'y')
loop = 'n';
}
return 0;
}
The problem I am having is after I compile the code, it stops when the correct answer is input rather than going on to ask if the user would like to do another quiz.
First of all, I am a total beginner to both C (and any programming) and Stack Overflow, so sorry if something like this has been asked before.
So I've been having trouble with my math operations code in the loop part. When I type in N or Y, the program acts as if I typed in a different option and says I have to type in Y or N.
Here's the code. Sorry if it's a jumbled mess, this is all I know so far.
#include <stdio.h>
int main() {
while (1) {
int choice1, choice2, num1, num2;
printf("\n [1] Addition\n [2] Subtraction\n [3] Multiplication\n [4] Division\n");
printf("\n Pick a choice: ");
scanf("%d", &choice1);
printf("\n Give a number: ");
scanf("%d", &num1);
printf("\n Give another number: ");
scanf("%d", &num2);
switch (choice1) {
case 1:
printf("Sum is %d", num1+num2);
break;
case 2:
printf("Difference is %d", num1-num2);
break;
case 3:
printf("Product is %d", num1*num2);
break;
case 4:
printf("Quotient is %d", num1/num2);
break;
default:
printf("Please select a valid operation");
}
printf("\n Try another operation [y/n]: ");
scanf("%d", &choice2);
if (choice2 == 'y' || choice2 == 'Y') {
printf("Retrying...");
break; }
else if (choice2 == 'n' || choice2 == 'N') {
printf("Exiting...");
break; }
else {
printf("Pick y or n only");
break;
}
}
return 0;
}
the issue here is that in the if statement you are using break which breaks the flow, instead you should be using continue
major changes: (I've added comment line to make the changes more obvious for you)
int check = 1; //added a check variable
while (check) { //used check variable for while loop
printf("\n Try another operation [y/n]: ");
scanf("%c", &choice2); //changed %d to %c as the input is a char
if (choice2 == 'y' || choice2 == 'Y') {
printf("Retrying...");
continue; } //changed break with continue
else if (choice2 == 'n' || choice2 == 'N') {
printf("Exiting...");
check= 0; } //updated check so next iteration fails and terminates the loop
else {
printf("Error wrong input");
check= 0; //there cannot be a 2nd try using if else statement
}
there will be few more changes which I'll mark in the code below
#include <stdio.h>
int main() {
int check = 1; //added a check variable
while (check) { //used check variable for while loop
int choice1, choice2, num1, num2;
printf("\n [1] Addition\n [2] Subtraction\n [3] Multiplication\n [4] Division\n");
printf("\n Pick a choice: ");
scanf("%d", &choice1);
printf("\n Give a number: ");
scanf("%d", &num1);
printf("\n Give another number: ");
scanf("%d", &num2);
switch (choice1) {
case 1:
printf("Sum is %d", num1+num2);
break;
case 2:
printf("Difference is %d", num1-num2);
break;
case 3:
printf("Product is %d", num1*num2);
break;
case 4:
printf("Quotient is %d", num1/num2);
break;
default:
printf("Please select a valid operation");
}
printf("\n Try another operation [y/n]: ");
scanf("%c", &choice2); //changed %d to %c as the input is a char
if (choice2 == 'y' || choice2 == 'Y') {
printf("Retrying...");
continue; } //changed break with continue
else if (choice2 == 'n' || choice2 == 'N') {
printf("Exiting...");
check= 0; } //updated check so next iteration fails and terminates the loop
else {
printf("Error wrong input");
check= 0; //there cannot be a 2nd try using if else statement
}
}
return 0;
}
for more detail, you can read the docs
I think you will have to do some major changes as shown below
#include <stdio.h>
int main() {
while (1) {
int choice1, num1, num2;
char choice2;
printf("\n [1] Addition\n [2] Subtraction\n [3] Multiplication\n [4] Division\n");
printf("\n Pick a choice: ");
scanf("%d", &choice1);
printf("\n Give a number: ");
scanf("%d", &num1);
printf("\n Give another number: ");
scanf("%d", &num2);
switch (choice1) {
case 1:
printf("Sum is %d", num1+num2);
break;
case 2:
printf("Difference is %d", num1-num2);
break;
case 3:
printf("Product is %d", num1*num2);
break;
case 4:
printf("Quotient is %d", num1/num2);
break;
default:
printf("Please select a valid operation");
}
printf("\n Try another operation [y/n]: ");
scanf("%s", choice2);
if (choice2 == 'y' || choice2 == 'Y')
{
scanf("%d", &choice1);
}
else;
{
printf("Exiting...");
}
}
return 0;
}
I have to write a c program to manage the reservations. When I call back the main function the program gets terminated without continuing. How can I fix this error? ( I haven't written the whole program)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
int i, j, day, x;
char session[10];
int array[2][5] = {{0,0,1,0,1},{1,1,0,0,0}};
char response,ans,choice;
printf("**************** WELCOME TO NAT RESERVATION SYSTEM ****************");
printf("\n\nCHOOSE WHAT TO DO");
printf("\n\n\t\tA.\t\tBOOK THE THEATER");
printf("\n\t\tB.\t\tCHECK RESERRVATIONS");
printf("\n\t\tC.\t\tREMOVE RESERVATIONS");
printf("\n\t\tD.\t\tCALCULATE INCOME");
printf("\n\t\tE.\t\tEXIT");
printf("\n\nYOUR RESPONSE\t\t: ");
scanf("%c",&response);
switch (response){
case 'A': printf("\n\nBOOK THE THEATER"); break;
case 'B': printf("\n\nCHECK RESERRVATIONS"); break;
case 'C': printf("\n\nREMOVE RESERVATIONS"); break;
case 'D': printf("\n\nCALCULATE INCOME"); break;
case 'E': printf("\n\nEXIT"); break;
}
if (response == 'A'){
printf("\n\nCHOOSE A DAY : ");
scanf("%d",&day);
j = day -1;
printf("YOUR SESSION : ");
scanf("%c",session);
fgets(session,10,stdin);
if(strcmp(session,"MORNING")){
i = 0;
}else if(strcmp(session,"AFTERNOON")){
i = 1;
}else{
printf("PLEASE ENTER MORNING OR AFTERNOON");
}
if(array[i][j] == 0){
printf("\n\nTHE SESSION IS AVAILABLE.\nDO YOU WANT TO CONFIRM THE BOOKING?(Y/N) : ");
scanf("%c",&ans);
I want to direct the program to print the main menu. So I called back the main() function here.
if(ans == 'Y' || ans == 'y'){
array[i][j] = 1;
printf("\nYOUR BOOKING WAS SUCCESSFUL!\n\n");
main();
}
}else if(array[i][j] == 1){
printf("\n\nTHE SESSION IS NOT AVAILABLE.");
printf("DO YOU WANT TO TRY ANOTHER SESSION?(Y/N): ");
scanf("%c",&ans);
if(ans == 'Y' || ans == 'y'){
main();
}else if(ans == 'N' || ans == 'n'){
printf("THANK YOU! HAVE A NICE DAY!");
exit(0);
}
}
}
}
I tried to use a while loop. I don't know what to put inside the brackets. Please help me. I'm new to C programming as I learned most of them online.
while(1){
printf("**************** WELCOME TO NAT RESERVATION SYSTEM ****************");
printf("\n\nCHOOSE WHAT TO DO");
printf("\n\n\t\tA.\t\tBOOK THE THEATER");
printf("\n\t\tB.\t\tCHECK RESERRVATIONS");
printf("\n\t\tC.\t\tREMOVE RESERVATIONS");
printf("\n\t\tD.\t\tCALCULATE INCOME");
printf("\n\t\tE.\t\tEXIT");
printf("\n\nYOUR RESPONSE\t\t: ");
scanf("%c",&response);
switch (response){
case 'A': printf("\n\nBOOK THE THEATER"); break;
case 'B': printf("\n\nCHECK RESERRVATIONS"); break;
case 'C': printf("\n\nREMOVE RESERVATIONS"); break;
case 'D': printf("\n\nCALCULATE INCOME"); break;
case 'E': printf("\n\nEXIT"); break;
}
if (response == 'A'){
printf("\n\nCHOOSE A DAY : ");
scanf("%d",&day);
j = day -1;
printf("YOUR SESSION : ");
scanf("%c",session);
fgets(session,10,stdin);
if(strcmp(session,"MORNING")){
i = 0;
}else if(strcmp(session,"AFTERNOON")){
i = 1;
}else{
printf("PLEASE ENTER MORNING OR AFTERNOON");
}
if(array[i][j] == 0){
printf("\n\nTHE SESSION IS AVAILABLE.\nDO YOU WANT TO CONFIRM THE BOOKING?(Y/N) : ");
scanf("%c",&ans);
if(ans == 'Y' || ans == 'y'){
array[i][j] = 1;
printf("\nYOUR BOOKING WAS SUCCESSFUL!\n\n");
continue;
main();
}
}
if(array[i][j] == 1){
printf("\n\nTHE SESSION IS NOT AVAILABLE.");
printf("DO YOU WANT TO TRY ANOTHER SESSION?(Y/N): ");
scanf("%c",&ans);
if(ans == 'Y' || ans == 'y'){
continue;
main();
}else if(ans == 'N' || ans == 'n'){
printf("THANK YOU! HAVE A NICE DAY!");
exit(0);
}
}
}
Your original program without while and continue seems to work fine if you use scanf with the format string " %c", that is insert a blank space before the percentage sign. This makes the program skip leading white space. Without the leading space in the format string the newline characters in the input will not be skipped over.
NOTE: It is also better to print a newline at the end of a string. If I choose B, for instance, the program output does not end with a newline so on a non-Windows machine the command prompt (in my case a dollar sign) is displayed on the same line as the output:
CHECK RESERRVATIONS$
I need the code below to recognize if the grades entered is below 1 or greater than 100. If it is not within the parameters, I want to let the user know and allow them to enter another grade without exiting the program or losing grades they have already entered. I don't want the program to quit until the user enters q and I want to ensure all of the valid grades entered print at that time. I have tried numerous methods and am not getting the right results. I think I probably need some other else if statement, but I haven't been able to find the right one to work. Any information you can share to get me on the right track would be greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char choice;
int gradeArray[100];
int grades;
int gCount=0,i;
for(gCount=0; gCount<100; gCount++)
{
//for loop to read the grades till array size
printf("******Enter Choice Selection in Parenthesis******\n Add grades(a)\n Quit(q) \n");
scanf("%c",&choice);
if(choice == 'a' || 'A')
{
//if user choice is a, then read the grade
printf( "Enter grade: ");
scanf("%d", &grades);
getchar();
gradeArray[gCount] = grades; //add the grade to array
}
if(choice == 'q') //if the user choice is q, then exit the loop
{
break;
}
}
printf("Grades are:\n");
for(i=0; i<gCount; i++)
{
printf(" %d%%\n", gradeArray[i]); //print grades
}
return 0;
}
You can do a while loop to verify the user input. With a while you'll be able to force the user to enter the right grade.
if(choice == 'A' || choice == 'a'){
printf("Enter grade:");
scanf("%d", &grades);
getchar();
while(grade < 1 || grade > 100){
printf("You entered a wrong number\n");
printf("Enter a grade between 1 and 100: ");
scanf("%d", &grades);
getchar();
}
gradeArray[gCount] = grades;
}
your solution is almost aligned with what you had in mind. Here is how you can do it differently.
#include <stdio.h>
int main()
{
char choice;
int arraySize = 100; //change this to any number you wish
int gradeScore = 0;
int gradeArray[arraySize];
int gCount = 0;
int showCount = 0;
while(choice != 'q')
{
//to ask for user's input every time
printf("What do you want to do? Enter\n");
printf("'a' to add grades\n");
printf("'q' to quit\n");
scanf(" %c", &choice); //space is entered to ensure the compiler does not read whitespaces
//your implementation should check for user input before proceeding
if(choice != 'a')
{
//in this condition, 'q' is technically an incorrect input but your design states that 'q' is for quitting
//thus, do not alert the user here if 'q' is entered
if(choice != 'q')
{
//a condition to warn the user for incorrect input
printf("Incorrect input. Please enter only 'a' or 'q'\n");
}
}
else if(choice == 'a')
{
printf("Enter grade: \n");
scanf(" %d", &gradeScore);
//to check for user input if the grades entered are less than 1 or more than 100
if(gradeScore < 1 || gradeScore >100)
{
//print a warning message
printf("The grade you entered is invalid. Please enter a grade from 1 - 100\n");
}
//for all correct inputs, store them in an array
else
{
printf("Grade entered\n");
gradeArray[gCount] = gradeScore;
gCount++;
}
}
}
//prints grade when 'q' is entered
if(choice == 'q')
{
printf("Grades are: \n");
for(showCount = 0; showCount < gCount ; showCount++)
{
printf("%d\n", gradeArray[showCount]);
}
}
}
To sum up the important parts, be sure to check for the user grade input to be in range of 1 - 100. Store the grade in the array if it is within range and be sure to increase the array counter, otherwise it will always store it in gradeArray[0] for the subsequent grades. Hope this helps
Use a do-while loop to keep the program looping back to get another choice unless a valid choice has been entered. Use fgetc to read a single character - fewer problems. Only print grades if at least one grade has been entered.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char choice;
int gradeArray[100];
int grades;
int gCount=0,i;
for(gCount=0; gCount<100; gCount++)
{
//for loop to read the grades till array size
printf("******Enter Choice Selection******\n Add grades(a)\n Quit(q) \n");
do
{
choice = fgetc(stdin);
if(choice == 'a' || choice == 'A')
{
//if user choice is a, then read the grade
printf( "Enter grade: ");
scanf("%d", &grades);
getchar();
gradeArray[gCount] = grades; //add the grade to array
}
else if(choice != 'q')
printf("Invalid choice - try again\n");
} while (choice != 'a' && choice != 'A' && choice != 'q');
if(choice == 'q') //if the user choice is q, then exit the loop
break;
}
if(gCount > 0)
{
printf("Grades are:\n");
for(i=0; i<gCount; i++)
printf(" %d%%\n", gradeArray[i]); //print grades
}
return 0;
}
I need to write a script for the user to enter a score between 0 and 10, flush the bad input out, if user inputs it and then using a switch statement, tell a user what grade did he/she got.
Here is my script:
...
int main()
{
int input; // input from user
printf("Enter the number between 0 and 10 and I will tell you your grade!");
while ((input=scanf("Your input:", &input) != EOF))
{
if (input < 0 || input > 10) //input is invalid
{
printf("Sorry, invalid character data.");
while (getchar() !='\n')
{
printf("Your input must be from 0 to 10.", input);
scanf("%d", &input); //This part looks very bad for me
}
}
else
switch (input)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
printf("Your grade is F. \n");
break;
case 6:
printf("Your grade is D. \n");
break;
...
I got this far with my homework, and here are some "leftover" problems I can't fight with.
1) Whenever user submits anything after enter, it goes into infinite loop and prints Your grade is F., even when case = 6 for example.
2) I used break; at the end of each case. It looks like they don't work(?)
3) It looks like the problem in the second line in the second loop
scanf("%d", &input); //This part looks very bad for me
but then I guess the scripts accepts it as true since the else statements that includes switch begins to work, because otherwise it wouldn't print Your grade is F.
Try the following code. Have a look at what flush_stream is doing when we have invalid data...
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void flush_stream();
void flush_stream() {
char c;
do {
c = getchar();
}
while (!isdigit(c) && c != '\n');
ungetc(c, stdin);
}
int main(void) {
const char *prompt = "Input please: ";
int input; // input from user
printf("Enter the number between 0 and 10 and I will tell you your grade!\n");
while(1) {
printf("%s", prompt);
int ret = scanf("%d", &input);
if(ret == 0) {
printf("Sorry, invalid character data, your input must be from 0 to 10.\n");
flush_stream();
continue;
}
if(ret > 0) {
if (input < 0 || input > 10) {
printf("Sorry, invalid character data, your input must be from 0 to 10.\n");
flush_stream();
continue;
}
switch (input) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
printf("Your grade is F. \n");
break;
case 6:
printf("Your grade is D. \n");
break;
}
}
}
}
It seems you are using scanf and printf wrong.
To input a number:
scanf("%d", &input);
To output a number:
printf("%d\n", input);
And in you while loop, when the input is illegal, why not just continue to the next loop?
while (true) {
printf("input your grade here: ");
if (scanf("%d", &input) == EOF) {
break;
}
if (input < 0 || input > 10) {
printf("your input is illegal.\n");
continue;
}
switch (input) {
...
}
}