This question already has an answer here:
C++ Beginner Infinite Loop When Input Wrong Data Type and Help Evaluate My Code
(1 answer)
Closed 3 years ago.
When I try to call this function and provide a value to variable grade other than integer, the do-while loop kept on executing and don't even prompt for an input to the variable of type char. Kindly help me to figure out why loop kept on executing.
//User Input function
int userInput(){
int grade,question;
char choice='y';
srand(time(0));
do{
//displayMenu();
cout<<endl;
cout<<"Please select grades, use number 1 to 5: ";
cin>>grade;
/*if(grade<1 || grade>5){
cout<<"You have entered an invalid grade!"<<endl;
}
else{
cout<<"Enter number of questions you want to generate: ";
cin>>question;
while(question<1){
cout<<endl;
cout<<"You have entered an invalid number"<<endl;;
cout<<"Enter number of questions you want to generate: ";
cin>>question;
}
cout<<endl;
questionGenerator(grade,question);
cout<<endl;
cout<<"Press n/N to Quit or Press any key and then Enter";
cin>>choice;
system("cls");
}*/
cout<<"Type N/n to Quit or Press Any Key and then Enter"<<endl;
cout<<"Your choice? : ";
cin>>choice;
system("cls");
}while(choice!='n' && choice!='N');
return 0;
}
Well your grade variable is an intteger, so it cant take any other type of variable. If you are going to input a char then why is grade an integer or if you are going to inout a string? If you need this to be possible then maybe try using arrays and start turning them from arrays to: integers floats booleans strings or characters. Also be careful because a char value can be assigned to a number (character code).
Related
I am new at c++ and for an assignment I have a program that requires a switch within a while but i keep getting stuck in an infinite loop
I have tried looking up ways to solve it but since i am not skilled at c++, it is really hard for me to get my error
#include <iostream>
#include <stdio.h>
using namespace std;
int main(void)
{
float length, width, perimeter, area;
char ans;
cout<<"Please enter the length of the rectangle: \n";
cin>>length;
cout<<"Please enter the width of the rectangle: \n";
cin>>width;
cout<<"What do you wish to do with these values?\n";
cout<<"Choose an option from the menu: \n";
cout<<"1 - Calculate Perimeter\n";
cout<<"2 - Calculate Area\n";
cout<<"3 - Quit\n";
cout<<"Please enter your choice: \n";
cin>>ans;
while (ans != '3')
{
printf("give option: "); //found this online
ans = getchar(); //this too
switch (ans)
{
case '1' :
perimeter=2*(length+width);
cout<<"The perimeter of the rectangle with length "<<length<<" and width "<<width<<" is "<<perimeter<<endl;
break;
case '2' :
area=length*width;
cout<<"The area of the rectangle with length "<<length<<" and width "<<width<<" is "<<area<<endl;
break;
default :
cout<<"Invalid Entry, please only select options from menu"<<endl;
}
}
printf("Program finished...\n"); //this was online too
return 0;
}
when i enter the option 2 or 1, there is an infinite loop and i cant seem to fix that.
I am not use to formatting on this site, please excuse the way i formatted my code
getchar() is not the right function to use there. It returns all characters, spaces, newlines, etc.
If you add a line to output the value of ans right after that, you will notice all the values that are assigned to ans.
ans = getchar();
cout << "ans: " << (int)ans << endl;
To skip whitespaces from the stream, use
cin >> ans;
In addition, the logic to get ans inside the while loop is flawed. It should be after the switch statement. Otherwise, your program tries to read ans twice before the first execution of the switch statement.
Here's an updated version of the relevant code that works for me.
cout << "Please enter your choice: \n";
cin >> ans;
while (ans != '3')
{
switch (ans)
{
case '1' :
perimeter=2*(length+width);
cout<<"The perimeter of the rectangle with length "<<length<<" and width "<<width<<" is "<<perimeter<<endl;
break;
case '2' :
area=length*width;
cout<<"The area of the rectangle with length "<<length<<" and width "<<width<<" is "<<area<<endl;
break;
default :
cout<<"Invalid Entry, please only select options from menu"<<endl;
}
cout << "Please enter your choice: \n";
cin >> ans;
}
Here is some help regarding formatting : https://stackoverflow.com/editing-help.
Indent the entire code 4 spaces to the right for a code block.
You must also be able to see the preview below as you keep writing the question.
getchar() isn't the appropriate function to use here. Read about the nuance here : http://www.cplusplus.com/forum/general/193480/
cin will be more appropriate to use.
Also, analyse your code step by step. You have an input taking line outside the while loop, and one inside too. Realise why this is wrong and try fixing it.
Since this is an assignment question, I won't be telling you the answer, but hopefully lead you to understand where you are going wrong.
After you solve the problem, please go back and analyse why your original code did not work. It helps immensely.
This question already has answers here:
Why cin inside while doesn't stop to get user input?
(2 answers)
Closed 4 years ago.
When I give a character input to 'choice', default statement is executed repeatedly. 'cin' instruction is not blocking the execution.
#include<iostream>
using namespace std;
main()
{
int choice;
do{
cout<<"Enter your choice: ";
cin>>choice; //I'm giving character i/p even though 'choice' is int
switch(choice)
{
case 1:cout<<"\n 1 \n";
break;
case 2:cout<<"\n 2 \n";
break;
case 3:cout<<"\n 3 \n";
break;
case 4:cout<<"\n 4 \n";
return 0;
default:cout<<"An Invalid choice."<<endl;
}
}while(1);
cout<<"\n Hello";
}
The cout statement shouldnt be blocking, that would be the cin you are referring to.
In this case, cin reading in the value, but NOT the newline after it, so the next time you read a value, you are reading the newline.
So you need to read in the new line values before reading the next value.
Try the following code by giving end limit to choice variable.
main(){
int choice;
do{
cout<<"Enter your choice: ";
cin>>choice; //I'm giving character i/p even though 'choice' is int
switch(choice)
{
case 1:cout<<"\n 1 --\n";
break;
case 2:cout<<"\n 2 \n";
break;
case 3:cout<<"\n 3 \n";
break;
case 4:cout<<"\n 4 \n";
return 0;
default:cout<<"An Invalid choice."<<endl;
}
}while(choice>4);
cout<<"\n Hello";
}
The break always breaks the innermost loop.
A break statement terminates execution of the smallest enclosing switch or iteration statement.
If you want to break out of both loops, use a label and jump with goto.
So basically its going into infinite loop since your break is only getting out from switch case.
My program closes immediately when I enter a letter. It shows the rest of the code but I do not get to enter the other parts of it. The program closes immediately when entering letters but remains when entering numbers, up until the part where the program is supposed to show the copied information. I have tried putting getchar(); after every cin<<a; but it skips lines and I only get to enter few info. Here is my code:
* I am an extreme newbie, this is by far the longest code I've ever worked on.
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
using namespace std;
int main()
{
string a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,y,z;
cout<<"Enter Your Name:";
cin>>a;
cout<<"Enter Your Gender:";
cin>>z;
cout<<"Enter Your Age:";
cin>>b;
cout<<"Enter Your Address:";
cin>>c;
cout<<"Enter Your School:";
cin>>d;
cout<<"Enter Your Nickname:";
cin>>e;
cout<<"Enter Highest Educational Attainment:";
cin>>f;
cout<<"What are your skills?:";
cin>>g;
cout<<"How many years experience do you have in this field?:";
cin>>h;
cout<<"What kind of people would you like to have in the workplace?:";
cin>>i;
cout<<"What good values do you have?:";
cin>>j;
cout<<"What bad values do you have?:";
cin>>k;
cout<<"When is your birthday?:";
cin>>l;
cout<<"What is your Father's name?:";
cin>>m;
cout<<"What is your Mother's name?:";
cin>>n;
cout<<"Do you have any children?:";
cin>>o;
cout<<"What is your eye color?:";
cin>>y;
cout<<"What do you dislike?:";
cin>>p;
cout<<"How many are you in the family?:";
cin>>q;
cout<<"What is your favorite food?:";
cin>>r;
cout<<"Your name is:"<<a<<endl;
cout<<"You are a:"<<z<<endl;
cout<<"You are"<<b<<cout<<"years old."<<endl;
cout<<"You live in:"<<c<<endl;
cout<<"You studied in:"<<d<<endl;
cout<<"Your nickname is:"<<e<<endl;
cout<<"Your highest educational attainment is:"<<f<<endl;
cout<<"Your skills are:"<<g<<endl;
cout<<"You have"<<h<<cout<<"years of experience in this field."<<endl;
cout<<"You would like to have"<<i<<cout<<"in the workplace."<<endl;
cout<<"The good thing is, you are:"<<j<<endl;
cout<<"The bad thing is, you are also:"<<k<<endl;
cout<<"Your birthday is in:"<<l<<endl;
cout<<"Your father is:"<<m<<endl;
cout<<"Your mother is:"<<n<<endl;
cout<<"You have"<<o<<cout<<"children."<<endl;
cout<<"You have"<<y<<"eyes."<<endl;
cout<<"You dislike:"<<p<<endl;
cout<<"You are"<<q<<cout<<"in the family"<<endl;
cout<<"Your favorite food is:"<<r<<endl;
return 0;
system ("pause");
}
*Edit: Replaced float with string and added #include <string> at the start of the code. The only problem now is the program closing when it is supposed to show the output and when entering a space in the input the next questions are in one line.
if x is a float type or an integer type
std::cin >> x;
reads no letter from std::cin if std::cin starts with a character that cannot be a prefix for a float or an integer type.
So x remains to 0 and your input stream remains unchanged.
For the next
std::cin >> y;
with y of type float or integer, the same behavior occurs: y remains to 0 and your input stream std::cin still starts with a character that cannot be read by a float or an integer type.
This behavior goes on until the end of your program.
float a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,y,z;
Variable a and other of type float. Which means they can store values like 1,10.0,12.3546 e.t.c. As soon as you enter any invalid character for this data type this program will exit.
If you want to run your program try declaring all variable as std::string and take input via getline like this getline(std::cin,var).
P.S : I have assumed here that var is of type string.
This question already has answers here:
How to test whether stringstream operator>> has parsed a bad type and skip it
(5 answers)
Closed 7 years ago.
I am using netbean ide for c++ study
I would like to force the user to pick only number between 1 to 3
int displayMenu()
{
while(true)
{
cout<<"Please choose one of following options"<<endl;
cout<<"1. deposit"<<endl;
cout<<"2. withdraw"<<endl;
cout<<"3. exit"<<endl;
int input;
cin >>input;
if(input>=1 && input<=3 && cin)
{
return input;
break;
}
else
{
cout<<"You have only 3 options. Please chooses 1,2 or 3"<<endl;
}
}
}
It works fine if the input is int number
If input is less then 1 or greater than 3, this function re-ask user to input number btw 1 and 3.
However, if the input is character such as 'f', it does an infinite loop.
This function know that 'f' is wrong input..
I did my own research in the Internet.
!cin and cin.fail() do not work.
Can you help me?
When you try to read an integer but pass something else, the reading fails and the stream becomes invalid. Whatever caused the error remains in the stream. This leads to infinite loop.
To fix that, clear the error flags and ignore the rest of the line in your else clause:
else
{
cout<<"You have only 3 options. Please chooses 1,2 or 3"<<endl;
cin.clear(); // remove error flags
// skip until the end of the line
// #include <limits> for std::numeric_limits
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
You can modify it like this:
int displayMenu()
{
while(true)
{
cout<<"Please choose one of following options"<<endl;
cout<<"1. deposit"<<endl;
cout<<"2. withdraw"<<endl;
cout<<"3. exit"<<endl;
char input = cin.get(); //read a character
cin.ignore(numeric_limits<streamsize>::max(), '\n'); //skip the rest of characters in cin buffer so that even if a user puts "123" only the first one is taken into account
if(input>='1' && input<='3' && cin) //check whether this is '1', '2' or '3'
{
return input;
break;
}
else
{
cout<<"You have only 3 options. Please chooses 1,2 or 3"<<endl;
}
}
}
This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 8 years ago.
I have a c++ program.I am using a do while loop to re execute the program after every cycle if the user chooses to run it again.The program runs fine on the first loop but on the subsequent runs the program skips requesting for a diver's name.It just prints the prompt for diver's name and number of judges together as shown below.How can i correct that?
On first run,notice the user is prompted to enter the number of judges after entering the diver's name as below
On the subsequent runs,the program does not wait for user to input the diver's name before requesting for the number of judges,it prints the two prompts together and only number of judges can be input as shown below
And here is the main class which holds the logic of execution:
int main()
{
char rerun;
do{
srand(time(NULL));
int number_of_judges=0;
char option,dive;
char dives[3];
string divenames[3];
double** scores;
string diverName="";
cout<<"What is the diver's name? "<<endl;
getline(cin,diverName);
number_of_judges=getjudges();
cout<<number_of_judges;
displayMenu();
for(int i=0;i<3;i++){
cout<<"Enter dive "<<i+1<<" to be judged(A-E)";
cin>>dive;
dive=tolower(dive);
while(!(dive=='a' || dive=='b' || dive=='c' || dive=='d' || dive=='e' ) ){
cout<<"You entered the wrong choice.Choice must be from (a-e)."<<endl;
cout<<"Enter dive "<<i+1<<" to be judged(A-E)";
cin>>dive;
dive=tolower(dive);
}
dive=tolower(dive);
dives[i]=dive;
}
for(int i=0;i<3;i++){
divenames[i]=getDive(dives[i]);
}
scores=getRandom();
getScores(diverName,scores,divenames);
cout<<"Do you want another try?";
cin>>rerun;
while(rerun !='y' && rerun!='n'){
cout<<"You have entered an invalid option.\nPlease try again.";
cin>>rerun;
rerun=tolower(rerun);
}
}
while(rerun=='y' || rerun == 'Y');
std::getchar();
return 0;
}
Any help will be greatly appreciated.
In the line:
cin>>rerun;
a charachter is extracted from the stream. This operation, however, leaves a newline in the buffer. So, when in the next step, you do:
getline(cin,diverName);
you are trying to read all the input up to newline and in the buffer there is already a newline (coming from the previous step): then this operation ends immediately.
The solution is to add an instruction after cin>>rerun of this type:
cin.ignore();
in this manner the newline left in the buffer will be discarded in the next operation.