how to exit if user enter q - c++

When user presses Q it doesnt quit from the program.. What is wrong?? Help please
while (true)
{
//promt to user enter or quit
cout<<" Enter five digit number please or Q to quit \n";
cin>> buf; n = atoi (buf.c_str());
cin.ignore(1000,10);
if( n == 'q' || n == 'Q')
break;
a = n % 10;
b = n / 10000;
if ( ! a == b )
{
cout<< "This is not a palindrome \n";
continue;
}
// checking the palindrome
n = n % 10;
n = n / 100;
if ( a == b )
cout<<" This is palindrome\n";
else
cout<<" This is not a palindrome\n";
}

if you enter a 'q' character, the atoi function can not interpret this input as a number so a zero is returned.
Please refer to this link
http://www.cplusplus.com/reference/cstdlib/atoi/
The most important is the following paragraph:
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed and zero is returned.
In this case str == buf

If you enter q or Q to this program, it won't convert anything in atoi, and n will be 0, not 'q' or 'Q'. The program will exit if you enter the numeric value for 'q' or 'Q' in your character set, though (113 or 81, respectively).
Example:
Enter five digit number please or Q to quit
12345
This is not a palindrome
Enter five digit number please or Q to quit
12321
This is palindrome
Enter five digit number please or Q to quit
q
This is palindrome
Enter five digit number please or Q to quit
113
I'll leave the further debugging/fixing to you. Note - your program doesn't correctly check for palindromes.

As stated in previous answers, q will be converted to 0 with atoi(). So, basically, in order for the program to quit with a q or Q, use the atoi() conversion after
if( n == 'q' || n == 'Q')
break;
This way, n will still be q or Q when you check if the program should quit, and if not, you then convert n to an integer with atoi() and check if it is a palindrome.
Hope I could help

Try changing
if( n == 'q' || n == 'Q')
to
if( buf[0] == 'q' || buf[0] == 'Q')
This will access the first character in the input and compare it with the desired character 'Q' or 'q'

Related

cin.fail with extra conditions C++

So I need to get input from the user which has to be a number and I have to use cin.fail() to check if it is a number. On top of that, the number has to be either 0, 1 or 2. I'm new to C++ so haven't figured out how to do it.
Here's the part of the code. It checks if the input is a number, but I do't know how to make it check if the number is 1, 2 or 0 and if not then ask again until the input is valid.
do {
input = false;
cout << "Enter a number from the menu: ";
cin >> menu;
if (cin.fail()) {
cout << "Invalid input!" << endl;
input = true;
cin.clear();
}
cin.ignore(numeric_limits<streamsize>::max(), '\n');
} while (input);
cout << "Valid input!";
Assuming menu is an integer, witch makes sense, you can add the conditions you mentioned to your if:
if (cin.fail() || menu < 0 || menu > 2)
Live sample
Assuming the variable menu is a string ,you can take the first character of the string menu in the if statement and check if the decimal value of the character is between the decimal number of '0' to '3'.
Change your if statement to this:
if (menu[0] < '0' || menu[0] > '3' || menu.length() > 1)
{
// Error code
}
This code will run only if the decimal value of the first character is smaller than the decimal value of the char '0' or bigger than the decimal value of the char '3' and this code will run if the length of the input the user entered is bigger than 1.

How to bail out of a while loop once a certain value is inputted into a variable

I'm making a program that uses a while loop in C++. Here is my code so far:
int userInput = 0;
while (userInput != 'Z')
{
cout << "Please enter the homework score: ";
cin >> userInput;
homeworkScores.push_back(userInput);
if (userInput == 'Z') {
userInput = 'Z';
}
}
The problem im having is whenever I type Z, the loop keeps printing "Please enter the homework score: " over and over without stopping. I've defined homeworkScores as a vector earlier in the code. How can I make it stop the loop once userInput == 'Z'? Thanks in advance!
The problem you are facing, is that cin is trying to read an integer, but you provide a character in the input. cin will only ask for another input, once the input is empty, you can try this by supplying more than one integer to your code:
Please enter the homework score: 2 27 12 8
will input all four numbers and print "Please enter the homework score: " 4 additional times.
If you provide it with a character, it will not remove it from the input, so whenever "cin" is reached, it will see "Z" in the input, and continue.
You can use answers like provided here How to catch invalid input in c++? for your input sanitation, but it will not make "Z" work as a stop.
The easiest way is to chose an invalid score like -1 instead of Z, end on any invalid input or try to read a string on failure to read an int.
A simple way to exit a loop is by using the break statement.
if (userInput == 'Z') {
userInput = 'Z';
break;
}
Other ways would be to set your exit condition to resolve as false, which I think is causing some issues for you.
EDIT: As #Ganea Dan Andrei noted, reading a char from cin into an integer will cause the cin::fail() to return true. This can be reset by calling cin.clear(), which will allow you to make further inputs.
userInput is an integer, and so 'Z' would have to equal the ASCII equivalent of its char value, which is 90. The way you're doing it should shouldn't work. Instead, try making userInput a char, and then convert it to an integer so you can push it back into your vector. This might look like:
char userInput = '';
while (userInput != 'Z')
{
cout << "Please enter the homework score: ";
cin >> userInput;
homeworkScores.push_back(userInput - '0'); //Are you sure you want to push a 'Z'?
if (userInput == 'Z') {
userInput = 'Z';
break;
}
userInput = ''; // Reset your input so it doesn't keep getting pushed new values
}
What happens here is userInput - '0' is subtracting the ASCII values of your chars, and leaving you with their integer value. There are other ways to do this, but this is a commonly used way.

While loop not terminating C++

I would like to keep inputting integers to the P1 vector until a break point in this case 'q' or 'Q' is entered. The program when ran goes crazy into an endless loop once the break condition is met. Any ideas on a work around, all I can see is that because the 'q' or 'Q' is a character the integer vector is taking this as an input when the while loop runs at which point it endless loops?
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
int main()
{
//Declaring Polynomial 1 and 2
vector<int> P1;
vector<int> P2;
int x = 0;
int y = 0;
while (x != 'q'||x != 'Q') {
cout << "Please enter in the first polynomial one value at a time (Press Q when done)...";
cin >> x;
P1.push_back(x);
}
//Also tested with a do while same problem
/*do
{
cout << "Please enter in the first polynomial one value at a time (Press Q when done)...";
cin >> x;
P1.push_back(x);
} while (x != 'q');*/
//Ignore this is for next part of program
vector<int> Res((P1.size() + P2.size()) + 1);
cout << P1.size() << "," << P2.size() << "," << Res.size();
return 0;
}
(x != 'q'||x != 'Q') <---- here is an error, it is obviously always true: when x==q -> true, because (x! = 'Q') == true, and the other way around. change || to &&.
The condition:
(x != 'q' || x != 'Q')
is always true resulting in an endless loop. Why that is in more details:
The x integer variable is initialized to 0. Then you check if x is different than 'q' which represents an integer value of 111. It is not equal to that value so the expression of x != 'q' is true. Then you check if x is not equal to 'Q' character which represents an integer value of 85. It is not equal to that value so the expression of x != 'Q' is also true. We end up with a condition of (true || true) which is always true.
Integral values are implicitly convertible to boolean values where 0 represents false and any other number represent true. Try something like this instead:
char c = 'y';
while (std::cin && (c == 'y' || c == 'Y')) {
// do work
std::cout << "Do you want to repeat the input? y / n?";
std::cin >> c;
}
That being said you don't need the "stdafx.h" header.
First I think you should not use int x
Second just like Ron said change || to &&
Anyway, Ron gave an example and it works.

Do.. while loop: How should I do so that the input (int) does not include digit '1' or '0'?

do
{
cout << "Enter a positive integer: ";
cin >> n;
}while ( n <= 1 || n == 0);
How should I code so that if I enter '1234', it would reject because there is a digit '1' there.
One approach would be to input a std::string from the user, and use std::string::find to see if 0 or 1 are present. Once you're done with that, attempt to convert the string to an integer.
Alternatively, if you want to keep everything "numeric", you can always use % 10 to extract the rightmost digit:
if (n % 10 < 2){
/*not allowed: I'm assuming n is positive here*/
}
Followed by
n /= 10
to remove that digit, and repeat, until you're left with zero. Obviously you'll need to test the special case of n starting at 0 separately.

how do you take in the enter key as an input?

I have been trying to take the enter key in as an input for my program. I have defined a char ENTER variable and used cin >> ENTER; to take in the enter key. Then I have used an if statement to determine whether the Enter key was press. if(ENTER == '13'), '13' is the ascii code for enter. It doesn't seem to be working, any suggestions?
How to detect the Enter Key without corrupting valid input:
char c;
cin.get(c); // get a single character
if (c == 10) return 0; // 10 = ascii linefeed (Enter Key) so exit
else cin.putback(c); // put the character back and proceed normally
Alternatively:
char c;
c = cin.peek(); // read next character without extracting it
if (c == '\n') return 0; // linefeed (Enter Key) so exit