'cin' inside loop: read error [duplicate] - c++

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.

Related

How do i prioritize the switch() case rather than other function

So i make a turn based dos game, And i have a switch() function which gives me a bug.. :
int hp;
int mana;
do
{
cout<<"Enter your arg here";
cin>>choice;
cout<<"Hahaha that won't stop me";
switch(choice)
{
case 1:
mana--;
mana--;
hp--;
hp--;
cout<<"Woosh";
}
}
while(1)
{
cout<<endl;
}
Ok so let me explain the bug :
When the player inputs choice variable it will just skip the switch() function an just go continue with cout<<"Hahaha that won't stop me";. How do i fix that?
PS : Sorry for my bad english, and if there is a misswriting on this post. I'm so sorry about that.
First of all, switch is not a function, it's a statement. That means, it doesn't behave like functions. What you've written here doesn't match with what you want.
What the program does is:
printing the first line
reading the input
printing the second line
switching on the input
What you want is:
printing the first line
reading the input
switching on the input
printing the second line on default case
So let's reorder your code.
cout << "Enter your arg here";
cin >> choice;
switch (choice)
{
case 1:
mana -= 2;
hp -= 2;
cout << "Woosh";
break;
default:
cout << "Hahaha that won't stop me";
break;
}
And don't forget to write break; on every case, including default one.

Why is my switch case which is inside a do while loop not working and breaks out of the loop even when it should continue?

Expected behavior is to take the name as input and run the while loop again but instead it just goes to the next line and does nothing.
#include <iostream>
using namespace std;
int main()
{
int ch,mb;
bool y=true;
char name;
cout<<"Enter 1,2 or 3 : ";
do{
cin>>ch;
switch(ch)
{
case 1:
cout<<" \n\t 1.ENTER CUSTOMER NAME :";
cin>>name;
continue;
case 2:
cout<<" \n\t 2.ENTER MOBILE NUMBER:";
cin>>mb;
continue;
case 3:
y=false;
}
}while(y!=false);
}
It doesn't "do nothing"; it waits for the next input. Because that's what you told it to do!
If you want to get another prompt, move the cout<<"Enter 1,2 or 3 : "; line inside the loop.
By the way, a char is one byte so that's not really appropriate for reading a whole customer name; furthermore, you should avoid using ints for telephone numbers.
Use break; instead of continue;
break will move execution to the end of the switch.
Edit: I think the issue is that you are just not seeing your prompt again. so move it inside your loop.

Running as infinite loop [duplicate]

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).

When I call a function within a function it skips code and terminates program?

It is a big program. I stripped off unnecessary code. I left only one of the key functions
When I call ss(); in any function the function gives control back to main() without accepting a string.
The code works if I don't use a function to accept the string. I can't find anything wrong with it.
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<ctype.h>
void ss();
void casechange();
using namespace std;
char str[100];
int main (){
int choice;
cout<<"Make a choice"<<endl;
cout<<"Press 1 to change the case of alphabets"<<endl;
cout<<"Press 2 to count number of vowels"<<endl;
cout<<"Press 3 to check if entered string is a palindrome or not"<<endl;
cout<<"Press 4 to reverse a string"<<endl;
cout<<"Press 5 to count number of words"<<endl;
cin>>choice;
switch(choice){
case 1: casechange();
break;
case 2: vowelcount();
break;
case 3:pal();
break;
case 4: rev();
break;
case 5: wordcount();
break;
default: cout<<"Wrong choice"<<endl;
}
return 0;
}
void casechange(){
ss();
for(int i=0;str[i]!='\0';i++)
{
if(isupper(str[i]))
str[i]=tolower(str[i]);
else str[i]=toupper(str[i]);
}
puts(str);
}
void ss()
{
cout<<"Enter a string"<<endl;
gets(str);
}
p.s. I am using code blocks. gcc compiler I guess.
You asked user to make a choice. User typed a number and enter. You then read a single character. enter still sitting there in the buffer. When it comes to gets, it reads it as an empty string.
Also please pay attention to all the comments about IO, gets etc.

Why does a loop not ask for command line input every cycle in C++? [duplicate]

This question already has an answer here:
Why does cin.clear() fix an infinite loop caused by bad input to cin?
(1 answer)
Closed 7 years ago.
I have a small program written in C++ that requests command line input for the user's grade. If the input is valid (i.e. a number between 0 and 100), a switch is called to print something out based on the user's grade, and then the program exits successfully.
If the user enters a number that isn't a valid grade, the program successfully loops back and asks for valid input until the user enters an appropriate grade.
However, if the user enters a String that isn't a number at all, such as "no", the loop infinitely requests a valid grade without ever stopping to take input, ultimately crashing the command line.
The complete program:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main(int argc, char** argv) {
cout << "\nEnter your grade: ";
int grade;
// Infinite input loop.
while(true) {
// Is the String a valid grade?
if(cin >> grade && grade >= 0 && grade <= 100) {
switch(grade / 10) {
case 10:
case 9:
cout << "A is for \"Awesome\"!";
break;
case 8:
cout << "B is okay.";
break;
case 7:
cout << "C isn't okay.";
break;
case 6:
cout << "Bad luck.";
break;
case 5:
case 4:
case 3:
case 2:
case 1:
cout << "Ouch!";
break;
}
cout << "\n\n";
break;
} else {
cout << "Please enter a valid grade: ";
}
}
}
That is because the stream enters a failure state. When the fail bit is set in the stream all operations will fail. You need to call clear() on the stream to clear out the error flags and then you need to remove any extra input that could still be in the stream. You can do that with
cin.clear(); // clear error flags
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
You will need to include the <limits> header for this.