Where should i put a do while bool is true - c++

I wrote a program that outputs the name equivalent of a numerical grade the user wrote into the console.
1 being FAIL
2 being SATISFACTORY
3 being GOOD
4 being VERY GOOD
5 being EXCELLENT
Now I would like to ask the user does he want to continue inputting the grades AFTER the first one runs,
e.g
input grade
-> 5
Excellent
Would you like to continue inputting grades? 1 - yes/ 0 -no
I'm clueless where to put the do while bool is true..
int main()
{
int grade;
do
{
cout << "input your grade: \n";
cin >> grade;
if (grade < 1 || grade > 5)
{
cout << "input grade again!\n";
}
} while (grade < 1 || grade > 5);
switch (grade)
{
case 1:
cout << "fail\n";
break;
case 2:
cout << "satisfactory\n";
break;
case 3:
cout << "good\n";
break;
case 4:
cout << "very good\n";
break;
case 5:
cout << "excellent\n";
break;
}
return 0;
}

You just need another do-while statement to have a repeated process. I've initialized a char variable named userChoice (always make the initialization to avoid undefined behaviors and hard to track errors) to check in every iteration what user wants (to continue or to end the program).
//previous codes...
char userChoice = 'n';
do{
// previous codes which you want to be repeated
std::cout << "\nDo you want to continue ? (y = Yes, n = No ) "; // ask the user to continue or to end
std::cin >> userChoice; // store user's input in the userChoice variable
}while(userChoice); // if user's input is 'y' then continue with next iteration
//rest of the code...
Also, Why is "using namespace std" considered bad practice?

Related

Non integer input causes infinite loop

i created a code for my final project. where in the start the user is asked what calculator to use its either the average calculator or simple calculator. but if the user accidentally entered a non integer it causes in infinite error loop but if its an integer that is not in the choices it works because i created a while loop. i need help what do i need to do to prevent the infinite loop.
cout << 1. average calculator: << endl;
cout << 2. simple calculator: << endl;
cout << Enter the Number << endl;
cin >> choice;
while (choice > 2 || choice <= 1)
{
cout << "Error! Please choose a number between 1 and 2 only." << endl;
cout << "Enter the number again:";
cin >> choice;
}
You need to clear the input buffer. Also the condition in this if statement is incorrect
while (choice > 2 || choice <= 1)
It seems you mean
while (choice > 2 || choice < 1)
The while loop can be rewritten as do-while loop the following way
#include <limits>
//...
bool input_error = false;
do
{
input_error = false;
if ( not ( std::cin >> choice ) )
{
std::cin.clear();
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
input_error = true;
}
else if ( choice < 1 || choice > 2 )
{
input_error = true;
}
if ( input_error )
{
std::cout << "Error! Please choose a number between 1 and 2 only.\n";
std::cout << "Enter the number again: ";
}
} while ( input_error );
Instead of using a while loop, you could use a switch like this
switch(choice //this is the input)
{
case 1:
//the stuff you want to do
break; //always a break
case 2:
//more stuff
break;
default:
//throwing a error
std::cout << "Error, please pick a number between 1 and 2\n";
}
and if you want to repeat until you pick the right number, you could put the switch inside a do while loop like this
do
{
switch(choice)
{
//the stuff
}
}while(choice > 2 || choice < 1);
let's hope this will work
have a nice day.
cout << "1. average calculator:" << endl;
cout << "2. simple calculator:" << endl;
cout << "Enter the Number" << endl;
string stringInput;
getline(cin, stringInput);
int choice = atoi(stringInput.c_str());
while(choice < 1 || choice > 2) {
cout << "Error! Please choose a number between 1 and 2 only." << endl;
cout << "Enter the number again:";
getline(cin, stringInput);
choice = atoi(stringInput.c_str());
}
You should read whole line, store it in string, and then convert that string to integer using atoi(). atoi() expects c-string to be passed so std::string should be converted to c-string. It is done by stringInput.c_str().
I changed while condition(choice > 2 || choice <= 1) to (choice < 1 || choice > 2) because it says to enter number between 1 and 2, but with your condition entering number 1 would print "Error! Please choose a number between 1 and 2 only.".

Is there a way to input different value for the same data when the same function is called multiple times?

I'm creating a student data management program in C++ and the function to insert examination marks is buggy.
The code given below is enough to recreate the buggy part of the program.
I have tried to increase the size of sub[] to 16
I have tried to insert data one after the other instead of a loop
None of the above seem to solve the problem
Menu function:
char ch;
main_menu:
clrscr();
cout << "Press the key for your choice:\n";
cout << "D -> Edit details\n";
cout << "R -> Get result\n";
cout << "I -> Insert marks\n";
cout << "E -> Exit Program";
choice:
ch = getch();
switch(ch)
{
case 'd':
//edit_nam(); Ignore this one
goto main_menu;
break;
case 'i':
ins_mar();
goto main_menu;
break;
case 'r':
//get_res(); This one is not related to the problem
goto main_menu;
break;
case 'e':
break;
default:
goto choice;
}
Insert marks function:
for(int i = 0; i < 6; i++)
{
clrscr();
cout << "Enter details of subject:" << i + 1;
cout << "\nSubject name:";
cout << "\nMarks:";
gotoxy(14, 1);
cin.getline(student.marks[i].sub, 8);
gotoxy(7,2);
cin >> student.marks[i].mark;
(i != 5) ? cout << "\nPress any key to continue..." : cout << "\nPress any key to return to menu...";
getch();
}
Student structure:
struct stu
{
char name[20];
int ID;
int cls;
mar marks[6];
};
Marks structure:
struct mar
{
char sub[8];
float mark;
}
If the code was working fine, then it would ask the user to enter the marks for all six subjects, every time the function is called in one run.
However, It is not so. In the first time of function call, everything happens in the correct manner, but it does not ask for subject name after first subject in any of the other runs.

C++ received char for integer type cause switch case went wrong

I'm trying to write a simple program that will prompt user to input a number, then it will reply back to user that which number key has been key in. Inputs other than 0~9 should go to default case which has "Not allowed." message will be print as output. The following code:
#include <iostream>
#include<cstdio>
using namespace std;
int main()
{
int x;
cout << "Please enter number from 0~9: ";
cin >>x;
switch (x)
{
case 0: cout<< "0 is pressed.";break;
case 1: cout<< "1 is pressed.";break;
case 2: cout<< "2 is pressed.";break;
case 3: cout<< "3 is pressed.";break;
case 4: cout<< "4 is pressed.";break;
case 5: cout<< "5 is pressed.";break;
case 6: cout<< "6 is pressed.";break;
case 7: cout<< "7 is pressed.";break;
case 8: cout<< "8 is pressed.";break;
case 9: cout<< "9 is pressed.";break;
default : cout << "Not allowed.";
}
return 0;
}
So when I try to input non-integer such as 'a' or "abc", it will run the statement in case 0, instead of case default. Can anyone explain why? Isn't when an integer variable trying to store a character, it would take it's ascii as it's value? Hopefully someone are willing to explain the logic behind this. Thank you!
(I'm currently using getchar() and declaring variable x as char data type, as well as case '0' and so on to temporarily solve this problem. But I myself is interesting to learn the knowledge about this. Sorry if such post is duplicated, I tried to search and found none. Wish that my searching technique isn't that terrible.)
This is introduced in c++11, if std::cin extraction fails x is zero initialised.
If extraction fails, zero is written to value and failbit is set. If
extraction results in the value too large or too small to fit in
value, std::numeric_limits::max() or std::numeric_limits::min()
is written and failbit flag is set.
Obviously providing a letter when number is expected leads to extraction failure.
If you are not using c++11 and above then the value of x is whatever it was before the operation.
What you can do to rectify this is to read a char instead and compare it to char as well:
char x;
cout << "Please enter number from 0~9: ";
cin >> x;
switch (x)
{
case '0': cout << "0 is pressed."; break;
case '1': cout << "1 is pressed."; break;
//..the rest of cases..//
default: cout << "Not allowed.";
}
Alternatively, you could handle extraction failure and clear std::cin then prompt the user again:
#include <iostream>
#include <limits>
int main()
{
int x;
while (true)
{
std::cout << "Please enter 1, 22 or 155: ";
if (std::cin >> x)
break;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
switch (x)
{
case 1: std::cout << "1 is entered\n"; break;
case 22: std::cout << "22 is entered\n"; break;
case 155: std::cout << "155 is entered\n"; break;
default: std::cout << x << " is not an option, good bye!\n";
}
return 0;
}
Let me try to break it down:
int x; // will store 0 in x as it is the default value of int
cout << "Please enter number from 0~9: ";
cin >>x; // if you input a string this will fail, and cin should be in an error state,
// and the value of x is unchanged
switch (x)
{
case 0: cout<< "0 is pressed.";break; //< x is 0
...
You should check if cin has error'd in order to handle strings:
if (cin.fail()) {
//handle error
cin.clear() // reset cin error flags
}
once different type data enter in "cin" it takes default value of that type.
int x;
cout << "Please enter number from 0~9: ";
cin >>x;
input comes string, it return 0 as default value of int x.

Loops in C++ to Check Wrong Input and to Start Program Again if user enters Correct Input

I am new to c++. I have given assignment in which i have to calculate grades and ask input from the user. If he enter wrong input i have to start program again. If the user enters correct input i have to process data and again ask if he wants to check for another calculation.I have written this code so far. I don't know how to loop back again in the program if the user enters wrong input and to start program again if it is successful. Please Give me guidance over it. Thanks.
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
//Declaring Variable
char choice;
char input;
//Promptin User to Enter his/her Choice
cout<<"Enter C or c for Computer Science: \n" ;
cout<<"Enter S or s for Software Engineering: \n";
cout<<"Enter T or T for Telecom Engineering: \n";
cout<<"Select any option from the above Menu: ";
cin>>input;
if (input != 'c' || input != 'C'){
cout<<"Invalid input! Enter the correct input option again";
}else if (input != 's' || input != 'S' ){
cout<<"Invalid input! Enter the correct input option again";
}else if (input != 't' || input != 'T' ){
cout<<"Invalid input! Enter the correct input option again";
}else if (input == 'a' || input == 'A'){
}
system("pause");
return 0;
}
You can do it using a simple do while loop:
bool valid_input = false;
do
{
// Code to read and validate the input...
} while (valid_input == false);
If the input is valid, then you set valid_input to true and the loop will end.
On an unrelated note, if you don't case about upper- or lower-case, use e.g. std::tolower so you only have to compare the letter once. E.g. std::tolower(input)
!= 'c'.
Here is the code that will prompt the user for answer as long as the answer is defined withing switch statement. ans is a variable to hold a character either 1 or 0 corresponds to the user's input (defined in switch cases or not). If defined, then ans gets 1 other wise it gets value 0. Do While loop repeats while ans is 1 (defined within switch statement).
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
char input;
char ans; //correct answer, incorrect answer
do {
cout<<"Enter C or c for Computer Science: \n" ;
cout<<"Enter S or s for Software Engineering: \n";
cout<<"Enter T or T for Telecom Engineering: \n";
cout<<"Select any option from the above Menu: ";
cin>>input;
switch (input){
case 'S':
ans = 1;
break;
case 's':
ans = 1;
break;
case 'C':
ans = 1;
break;
case 'c':
ans = 1;
break;
case 'T':
ans = 1;
break;
case 't':
ans = 1;
break;
default:
ans = 0;
}
} while (ans);
return 0;
}
User input handling is very common and can normally use similar patterns.
Basically, you re-ask for the input. You handle the valid choices and break out of the loop and you show an error when the choice is invalid and let the loop ask the input again.
Remark1: by not using switch-case here, I can break out of the loop immediately. I break immediately to avoid specifying the conditions twice or using flags, that is also why I use a loop without end-condition.
Remark2: std::flush is used to input on the prompt line. It makes sure that the prompt is shown before waiting for input.
char inp = 0;
while (true) {
std::cout << "Give input (a, b): " << std::flush;
std::cin >> inp;
inp = std::tolower(inp);
if (inp == 'a') {
std::cout << 'a\n';
break;
}
if (inp == 'b') {
std::cout << 'b\n';
break;
}
std::cout << "invalid choice (" << inp << ")";
}
The invalid choice handling can be done a bit more generic by this function, but the handling of the valid choices must still be done locally:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
char askInputChoice(const std::string& prompt, const std::vector<char>& valid)
{
char inp = 0;
while (true) {
std::cout << prompt << ": " << std::flush;
std::cin >> inp;
inp = std::tolower(inp);
if (std::find(valid.begin(), valid.end(), inp) != valid.end()) {
break;
}
std::cout << "invalid choice (" << inp << ")\n";
}
return inp;
}
int main()
{
char inp = askInputChoice("Give input (a, b)", std::vector<char>{'a','b'});
switch (inp) {
case 'a':
std::cout << "a\n";
break;
case 'b':
std::cout << "b\n";
break;
}
}
To restart the program, put it in a while loop, add a choice to quit ('q') and break when that choice is given.
Thanks Guys for All Your Support. Actually it is my First Program in C++ and sorry i have used the word guidance. Actually i have compiled it successfully. Kindly Check my program i know u do not need to but i want to know if i can add more into it to improve it.
#include <cstdlib>
#include <iostream>
#include <conio.h>
using namespace std;
int main(int argc, char *argv[])
{
//Declaring Variable
char choice;
char input;
int addTest = 0, matricMarks = 0 , interMarks = 0 , result = 0;
start: //Label
system("cls"); // Clear the Screen
//Prompting User to Enter his/her Choice
cout<<"Please Select the Degree Programme in which you are interested in to take Addmission: ";
cout<<"\nEnter C or c for Computer Science: "<<endl ;
cout<<"Enter S or s for Software Engineering: "<<endl;
cout<<"Enter T or t for Telecom Engineering: \n"<<endl;
cout<<"\nSelect any option from the above Menu: ";
cin>>input;
//Switch Statement Started
switch(input){
//Case C Started
case 'c':
case 'C':
{
cout<<"Enter your Marks in Addmission Test: ";
cin>>addTest;
cout<<"Enter your Marks in Matric Degree: ";
cin>>matricMarks;
cout<<"Enter your Marks in Intermediate Degree: ";
cin>>interMarks;
result = (addTest * 0.20)+(matricMarks * 0.30)+(interMarks * 0.50);
if (result >= 70)
{
cout<<"\nCongratulations! You are eligible for the Computer Science degree program :)"<<endl;
}
else
{
cout<<"Sorry you Do not qualify for Computer Science Degree Programme: "<<endl;
system("pause");
}
break;
}//Case C Closeed
//Case s Started
case 's':
case 'S':
{
cout<<"Enter your Marks in Addmission Test: ";
cin>>addTest;
cout<<"Enter your Marks in Matric Degree: ";
cin>>matricMarks;
cout<<"Enter your Marks in Intermediate Degree: ";
cin>>interMarks;
result = (addTest * 0.20)+(matricMarks * 0.30)+(interMarks * 0.50);
if (result >= 85)
{
cout<<"\nCongratulations! You are eligible for the Software Enginnering degree program :)"<<endl;
}
else
{
cout<<"\nSorry! you Do not Qualify for Software Engineering Degree: "<<endl;
system("pause");
}
break;
}//Case S Closed
//Case t Started
case 't':
case 'T':
{
cout<<"Enter your Marks in Addmission Test: ";
cin>>addTest;
cout<<"Enter your Marks in Matric Degree: ";
cin>>matricMarks;
cout<<"Enter your Marks in Intermediate Degree: ";
cin>>interMarks;
result = (addTest * 0.20)+(matricMarks * 0.30)+(interMarks * 0.50);
if (result >= 80)
{
cout<<"\nCongratulations! You are eligible for the Telecom Engineering degree program :)"<<endl;
}
else
{
cout<<"Sorry you Do not Qualify for Telecom Enginnering Degree Programme: "<<endl;
system("pause");
}
break;
}//Case t Closed
//Default Case Started
default:
{
cout<<"\nInvalid input! Enter the correct option again: \n";
system("pause");
goto start; //Jump To Label Start
}//Deafult Case Closed
}// Switch Statement Close
//do while Loop Started
do{
cout<<"\nDo you want to check your eligibility in some other degree program y/n? : ";
cin>>choice;
if (choice=='Y'||choice=='y')
{
goto start; //jump to Label start:
}
else if (choice=='N'||choice=='n')
{
break;
}
}while(choice == 'y' || choice == 'Y');
//Do while Loop Closed
system("pause");
return 0;
}

problems with switch statement involving functions [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
This program is not prompting me for input. I need help with defining, and calling functions properly. menu() is supposed to display a string of text, and ask the user to select a number 1-4, and if the user enters a number outside of that it will ask the user to enter an appropriate number until 1-4 is entered. The value of menu() will be stored in a variable 'choice' and be used in a switch statement.
Inside of the switch statement the corresponding choice functions[getSum(), getFactor(), getExpo(), and exit()] are called. They each need to ask the user for an integer, and perform some arithmetic, and return some output text to the user with the calculated value.
All of this is inside of a do while loop repeating this process, until the user chooses the option 4 to quit the program, where the exit() function will return a string exit message to the user and then the program will terminate.
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int menu();
long int getSum();
long int getFactor();
long int getExpo();
string exit();
int main()
{
const int SUM = 1, // Summation choice
FACTOR = 2, // Factorial choice
EXPO = 3, // Exponential choice
QUIT = 4; // Exit choice
int choice; // Numerical menu choice
long int sums, facts, expos;
string quits;
// Force the console to print standard notation
cout << fixed << setprecision(0);
// Do-While loop controlled by the users choices
do
{
choice = menu();
switch (choice) // Start switch option
{
case SUM: // 1st choice
sums = getSum();
break;
case FACTOR: // 2nd choice
facts = getFactor();
break;
case EXPO: // 3rd choice
expos = getExpo();
break;
case QUIT: // 4th choice
quits = exit();
break;
default: // Default choice
// Error message for input outside domain
cout << "Please make a selection of either 1,2,3 or 4.\n\n";
cin >> choice; // Repeat attempt to gather input from user
}
}
while (menu() != QUIT);
return 0;
}
int menu()
{
int choice;
cout << "\n\t\tMathematical Menu\n" // Header
<< "1) Summation\n" // 1st choice
<< "2) Factorial\n" // 2nd choice
<< "3) Exponential\n" // 3rd choice
<< "4) Exit Program\n\n" // 4th choice
<< "Please make a selection\n" // Ask user for imput choice
<< "of either 1,2,3 or 4.\n\n";
cin >> choice; // Gather input from user
return choice;
}
long int getSum()
{
int total = 0, userNum, counter;
// Ouput statement to user
cout << "Please enter a positive integer value greater than 0 \n"
<< "and less than 10,000,000.\n\n";
cin >> userNum; // Repeat attempt to gather input from user
// Compare input to domain
if (userNum < 0 || userNum > 10000000)
{
// Error message for input outside domain
cout << "Please check your entry and try again.\n\n";
cin >> userNum; // Repeat attempt to gather input from user
}
// Perform arithmetic summation
for (counter = 1; counter <= userNum; counter++)
{
total += counter; // Running count
}
cout << "The total value for the added numbers 1 to \n"
<< userNum << " is:\n"<<total;
return total;
}
long int getFactor()
{
int total, userNum, counter;
total = 1;
// Output statement to user
cout << "Please enter a positive integer from 0 \n"
<< "and less than 100.\n\n";
cin >> userNum; // Gather input from user
// Compare input to domain
if (userNum > 100 || userNum < 0)
{
// Error message if input is outside domain
cout << "Please check your entry and try again.\n\n";
cin >> userNum; // Repeat attempt to gather input from user
}
// Perform arithmetic factorial
for (counter = 1; counter <= userNum; counter++)
{
total *= counter; // Running count
}
// Display arithmetic output to user
cout << "The total value for the multiplied numbers 1 to \n"
<< userNum << " is:\n";
return total;
}
long int getExpo()
{
int total, userNum, counter;
total = 0;
// Output statement to user
cout << "Please enter a positive integer from 0 \n"
<< "and less than 100.\n\n";
cin >> userNum; // Gather input from user
// Compare input to domain
if (userNum > 100 || userNum < 0)
{
// Error message if input is outside domain
cout << "Please check your entry and try again.\n\n";
cin >> userNum; // Repeat attempt to gather input from user
}
// Perform arithmetic exponential
for (counter = 1; counter <= userNum; counter++)
{
total = pow(2.0, userNum); // Running count
}
// Display arithmetic output to user
cout << "The total value for the exponential function is \n";
return total;
}
string exit()
{
// Exit message
return "Don't be gone for too long...\n";
}`
Do not call menu() more than once: it will prompt the user twice.
Do not return anything from a function that does all the work anyway. Make it
void getExpo(){ ...; return; }
Call:
getExpo();