String Input error when using stringstream and if-else statement - c++

I am trying to write a part of a large code where a string of 2 numbers is inputted by the user and each number is parsed from the string to do simple addition (just wanted to test the parsing for now).
I do the parsing using stringstream which seems to work but using this code to compute multiple cases is not working. Please see code and output below;
#include <iostream>
#include <sstream>
int main()
{
int t;
std::cout << "Enter the number of test cases: ";
std::cin >> t;
std::cout << std::endl;
if (t > 10 || t < 1)
{
std::cout << "Invalid number of test cases!" << std::endl;
return 0;
}
else
{
for (int x = 0; x < t; x++)
{
std::stringstream numbers;
int num_1;
int num_2;
std::cout << "Enter the two numbers (separated by a space): " << std::endl;
std::string input;
getline (std::cin, input);
numbers << input;
numbers >> num_1 >> num_2;
std::cout << num_1 << std::endl;
std::cout << num_2 << std::endl;
std::cout << num_1 + num_2 << std::endl;
}
}
return 0;
}
Code Output
CODE OUTPUT
Enter the two numbers (separated by a space):
0
-13120
-13120
Enter the two numbers (separated by a space):
1 3
1
3
4
Enter the two numbers (separated by a space):
4 5
4
5
9
Enter the two numbers (separated by a space):
6 7
6
7
13
Why is the first case not taking inputs?

Change code early in main to this:
std::cout << "Enter the number of test cases: ";
std::cin >> t; std::cin.ignore();
When you cin>>t, it reads in the number you give it and then stops. Your next input is a getline, which reads to the next end of line...which is the one you typed after the number of test cases. So you're using an empty line for your first input.
cin.ignore() tells it to skip that empty line and go on to whatever you type next.

First, using a value from cin without checking the stream state is almost as bad as using an uninitialized value. Take advantage of the streams explicit bool operator. Second, you are over complicating the code, why would you read in a string of numbers, only too parse them as numbers?
You can simply do this: with an arbitrary number of objects:
cin >> arg1 >> arg2 >> arg3 >> ...
I've modifed your code with these issues in mind:
#include <iostream>
#include <sstream>
int main()
{
int t;
std::cout << "Enter the number of test cases:\n";
if (std::cin >> t) { // succeeded in getting an int
if (t > 10 || t < 1) { // failed in getting a valid number of test cases
std::cout << "Invalid number of test cases!" << std::endl;
return 1; // return value of 0 is reserved for a successful run, returning zero after an error doesn't make sense
}
else { // succeeded in getting a valid number of test cases
for (int x = 0; x < t; x++) {
int num_1;
int num_2;
std::cout << "Enter the two numbers (separated by a space): " << std::endl;
// why use a stringstream here when you can get the same affect by just retrieving
// two integers from cin
if (std::cin >> num_1 >> num_2) { // again always check for valid input
std::cout << num_1 << std::endl;
std::cout << num_2 << std::endl;
std::cout << num_1 + num_2 << std::endl;
}
else { // failed in getting two int's
//...
// handle error
}
}
}
}
else {
//...
// handle error
}
return 0;
}

Related

How to allow a user to enter one or two inputs?

Say you wanted a user to enter a base for a root, and another number for the root. But, if the user only provides 1 number, the 2nd input will default to 2, so a square root.
I want to know how to stop the input if 'enter' was pressed after entering only one number.
I am using c++.
you may try this code:
#include <iostream>
using namespace std;
int main() {
int x, y;
int sum;
cout << "Type a number: ";
cin >> x;
cout << "Type another number: ";
cin >> y;
sum = x + y;
cout << "Sum is: " << sum;
return 0;
}
You probably are familiar with std::cin - that does not distinguish between enter and space for number input; that is, if your write:
int a, b;
std::cin >> a;
std::cin >> b;
Your program will expect 2 numbers, accepting both
1
2
or
1 2
What you want to do sounds like you only want to accept the second format, and decide based on the user input whether it contains one or two numbers. For that, use std::getline:
std::string line;
std::getline(std::cin, line);
Then, you need to "tokenize" the line, i.e. split it into parts separated by spaces:
std::string::size_type pos = line.find(' ');
if (pos == std::string::npos)
{
// only 1 input
}
else
{
// more than 1 input, split, e.g. with "line.substr(...)"
}
Full code:
#include <iostream>
int main()
{
std::string line;
std::getline(std::cin, line);
std::string::size_type pos = line.find(' ');
if (pos == std::string::npos)
{
int firstnum = atoi(line.c_str());
std::cout << "One number: " << firstnum << "\n";
}
else
{
int firstnum = atoi(line.substr(0, pos).c_str());
int secondnum = atoi(line.substr(pos+1, line.size()-pos).c_str());
std::cout << "Two numbers: " << firstnum << ", " << secondnum << "\n";
}
return 0;
}
Test run with one number:
1
One number: 1
Test run with two numbers:
1 2
Two numbers: 1, 2
Here we currently ignore the possibility of the user entering more than two numbers. You could check that, again with line.find, this time starting from pos+1 (see second parameter). The above code also does not check whether the input string starts with a space, which would result in 0 being recognized as first input... so it might be a bit trickier than using std::cin (which automatically skips whitespace if used for numbers). Look into string tokenization for more resilient ways of splitting the input.
I got your mean, you can use ASCII to help you.
Below is the code:
#include<iostream>
using namespace std;
int main()
{
cout << "Enter two numbers:" << endl;
int num1;
int num2 = 2;
cin >> num1;
if (cin.get() == 32)
cin >> num2;
cout << num1 << "\t" << num2 << endl;
return 0;
}
In this way, if the user enter only one number with enter, the num2 will not be changed; If the user enter one number, then space, and enter another number, the num2 will be changed as the second num2.
You could use it as a reference to complete your sqrt function.

How to limit cin to integers within the int data range?

I am wondering how to only allow inputs for a cin which are within the int data range.
// This program counts the number of digits in an integer
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int i, k;
cout << setw(20) << "Value Entered" << setw(20) << "Number of Digits" << endl;
while(1==1)
{
k = 1;
cout << setw(10) << "";
cin >> i;
while(i > 2147483647 || i < -2147483648)
{
cout << setw(10) << "";
cin >> i;
}
while( i / 10 > 0)
{
i = i / 10;
k++;
}
cout << setw(30) << k << endl;
}
return 0;
}
With the method I have it just gets stuck in the loop repeating 1.
EDIT:
Sample Output Format (Required)
"Value Entered" "Number of Digits"
14 2
225 3
-1000 4
Sample Output (What I have)
Value Entered Number of Digits
45
2
456
3
258
3
-2546
4
The extraction will fail if the number falls outside of the range for the type that it's being read into. When this happens the state of the stream will be set to failure, so you simply need to check for this state, and then reset the stream to a valid state:
while (!(cin >> i)) {
cin.clear();
cin.ignore(numeric_limit<streamsize>::max(), '\n');
}
clear() clears the error flags and ignore() puts the stream on a new line so that new data can be read. You may need to include <limits> for the code to work.
The condition for your second loop should be while (i > 0). As you had it you were off by one digit.

My 1st Quiz - Issue (C++) [duplicate]

I was typing this and it asks the user to input two integers which will then become variables. From there it will carry out simple operations.
How do I get the computer to check if what is entered is an integer or not? And if not, ask the user to type an integer in. For example: if someone inputs "a" instead of 2, then it will tell them to reenter a number.
Thanks
#include <iostream>
using namespace std;
int main ()
{
int firstvariable;
int secondvariable;
float float1;
float float2;
cout << "Please enter two integers and then press Enter:" << endl;
cin >> firstvariable;
cin >> secondvariable;
cout << "Time for some simple mathematical operations:\n" << endl;
cout << "The sum:\n " << firstvariable << "+" << secondvariable
<<"="<< firstvariable + secondvariable << "\n " << endl;
}
You can check like this:
int x;
cin >> x;
if (cin.fail()) {
//Not an int.
}
Furthermore, you can continue to get input until you get an int via:
#include <iostream>
int main() {
int x;
std::cin >> x;
while(std::cin.fail()) {
std::cout << "Error" << std::endl;
std::cin.clear();
std::cin.ignore(256,'\n');
std::cin >> x;
}
std::cout << x << std::endl;
return 0;
}
EDIT: To address the comment below regarding input like 10abc, one could modify the loop to accept a string as an input. Then check the string for any character not a number and handle that situation accordingly. One needs not clear/ignore the input stream in that situation. Verifying the string is just numbers, convert the string back to an integer. I mean, this was just off the cuff. There might be a better way. This won't work if you're accepting floats/doubles (would have to add '.' in the search string).
#include <iostream>
#include <string>
int main() {
std::string theInput;
int inputAsInt;
std::getline(std::cin, theInput);
while(std::cin.fail() || std::cin.eof() || theInput.find_first_not_of("0123456789") != std::string::npos) {
std::cout << "Error" << std::endl;
if( theInput.find_first_not_of("0123456789") == std::string::npos) {
std::cin.clear();
std::cin.ignore(256,'\n');
}
std::getline(std::cin, theInput);
}
std::string::size_type st;
inputAsInt = std::stoi(theInput,&st);
std::cout << inputAsInt << std::endl;
return 0;
}
Heh, this is an old question that could use a better answer.
User input should be obtained as a string and then attempt-converted to the data type you desire. Conveniently, this also allows you to answer questions like “what type of data is my input?”
Here is a function I use a lot. Other options exist, such as in Boost, but the basic premise is the same: attempt to perform the string→type conversion and observe the success or failure:
template <typename T>
auto string_to( const std::string & s )
{
T value;
std::istringstream ss( s );
return ((ss >> value) and (ss >> std::ws).eof()) // attempt the conversion
? value // success
: std::optional<T> { }; // failure
}
Using the optional type is just one way. You could also throw an exception or return a default value on failure. Whatever works for your situation.
Here is an example of using it:
int n;
std::cout << "n? ";
{
std::string s;
getline( std::cin, s );
auto x = string_to <int> ( s );
if (!x) return complain();
n = *x;
}
std::cout << "Multiply that by seven to get " << (7 * n) << ".\n";
limitations and type identification
In order for this to work, of course, there must exist a method to unambiguously extract your data type from a stream. This is the natural order of things in C++ — that is, business as usual. So no surprises here.
The next caveat is that some types subsume others. For example, if you are trying to distinguish between int and double, check for int first, since anything that converts to an int is also a double.
There is a function in c called isdigit(). That will suit you just fine. Example:
int var1 = 'h';
int var2 = '2';
if( isdigit(var1) )
{
printf("var1 = |%c| is a digit\n", var1 );
}
else
{
printf("var1 = |%c| is not a digit\n", var1 );
}
if( isdigit(var2) )
{
printf("var2 = |%c| is a digit\n", var2 );
}
else
{
printf("var2 = |%c| is not a digit\n", var2 );
}
From here
If istream fails to insert, it will set the fail bit.
int i = 0;
std::cin >> i; // type a and press enter
if (std::cin.fail())
{
std::cout << "I failed, try again ..." << std::endl
std::cin.clear(); // reset the failed state
}
You can set this up in a do-while loop to get the correct type (int in this case) propertly inserted.
For more information: http://augustcouncil.com/~tgibson/tutorial/iotips.html#directly
You can use the variables name itself to check if a value is an integer.
for example:
#include <iostream>
using namespace std;
int main (){
int firstvariable;
int secondvariable;
float float1;
float float2;
cout << "Please enter two integers and then press Enter:" << endl;
cin >> firstvariable;
cin >> secondvariable;
if(firstvariable && secondvariable){
cout << "Time for some simple mathematical operations:\n" << endl;
cout << "The sum:\n " << firstvariable << "+" << secondvariable
<<"="<< firstvariable + secondvariable << "\n " << endl;
}else{
cout << "\n[ERROR\tINVALID INPUT]\n";
return 1;
}
return 0;
}
I prefer to use <limits> to check for an int until it is passed.
#include <iostream>
#include <limits> //std::numeric_limits
using std::cout, std::endl, std::cin;
int main() {
int num;
while(!(cin >> num)){ //check the Input format for integer the right way
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << "Invalid input. Reenter the number: ";
};
cout << "output= " << num << endl;
return 0;
}
Under C++11 and later, I have the found the std::stoi function very useful for this task. stoi throws an invalid_argument exception if conversion cannot be performed. This can be caught and handled as shown in the demo function 'getIntegerValue' below.
The stoi function has a second parameter 'idx' that indicates the position of the first character in the string after the number. We can use the value in idx to check against the string length and ascertain if there are any characters in the input other than the number. This helps eliminate input like 10abc or a decimal value.
The only case where this approach fails is when there is trailing white space after the number in the input, that is, the user enters a lot of spaces after inputting the number. To handle such a case, you could rtrim the input string as described in this post.
#include <iostream>
#include <string>
bool getIntegerValue(int &value);
int main(){
int value{};
bool valid{};
while(!valid){
std::cout << "Enter integer value: ";
valid = getIntegerValue(value);
if (!valid)
std::cout << "Invalid integer value! Please try again.\n" << std::endl;
}
std::cout << "You entered: " << value << std::endl;
return 0;
}
// Returns true if integer is read from standard input
bool getIntegerValue(int &value){
bool isInputValid{};
int valueFromString{};
size_t index{};
std::string userInput;
std::getline(std::cin, userInput);
try {
//stoi throws an invalid_argument exception if userInput cannot be
//converted to an integer.
valueFromString = std::stoi(userInput, &index);
//index being different than length of string implies additional
//characters in input that could not be converted to an integer.
//This is to handle inputs like 10str or decimal values like 10.12
if(index == userInput.length()) isInputValid = true;
}
catch (const std::invalid_argument &arg) {
; //you could show an invalid argument message here.
}
if (isInputValid) value = valueFromString;
return isInputValid;
}
You could use :
int a = 12;
if (a>0 || a<0){
cout << "Your text"<<endl;
}
I'm pretty sure it works.

C++ If else chain and nest for variable comparison

I'm writing a program that will take an 8 digit number as input by the user and will evaluate it so if any digit that appears more than 3 times will be labelled as "unacceptable"; if all digits appear 3 or fewer times it is labelled as "acceptable".
So these numbers:
41124535, 13134113, 24255411
would all be labelled as acceptable, but these ones
34233332, 31111412, 55551122
would be labelled as unacceptable.
My approach is if... else chains and nests. So far I've managed to make a chain work, but it can only compare the digits when they repeat up to 2 times. Then I have a nest, but it only works if I write the else part every step of the way, instead of just leaving one single else at the end. This is crucial since the else part in the end will take the algorithm to a new if else nest that will evaluate the rest of the 8 digit long number.
The beginning of the program:
cout << "\n\n\t Input 1st digit:";
cin >> A;
cout << "\t Input 2nd digit:";
cin >> B;
cout << "\t Input 3rd digit:";
cin >> C;
cout << "\t Input 4th digit:";
cin >> D;
cout << "\t Input 5th digit:";
cin >> E;
cout << "\t Input 6th digit:";
cin >> F;
cout << "\t Input 7th digit:";
cin >> G;
cout << "\t Input 8th digit:";
cin >> H;
cout << "\n\t The number is: [";
cout << A;
cout << B;
cout << C;
cout << D;
cout << E;
cout << F;
cout << G;
cout << H;
cout << "]";
the if...else chain:
if (A==B)
cout << " Unacceptable!";
else
if (B==C)
cout << " Unacceptable!";
else
if (C==D)
cout << " Unacceptable!";
else
if (D==E)
cout << " Unacceptable!";
else
if (E==F)
cout << " Unacceptable!";
else
if (F==G)
cout << " Unacceptable!";
else
if (G==H)
cout << " Unacceptable!";
else
cout << " Acceptable";
then the nest with several else commands:
if (A==B)
{
if (A==C)
{
if (A==D)
cout << " Unacceptable!";
else
cout << " Acceptable";
}
else
cout << " Acceptable";
}
else
cout << " Acceptable";
so my guess is an if...else chain with if...else nests for each variable, but I can't work it out.
I'm not sure if you are using nested if statements for a specific reason - challenge, etc.? I'll assume you're not.
You can read the digits as one string - you could read as an int, but then you have to extract the digits from that anyways.
std::string input;
std::cin >> input;
/* validate input, make sure that it's 8 digits,
* that they are all digits, etc. - hint: int isdigit(int c)
*/
You can use a std::map to keep a histogram of the digits.
std::map< char, int > digit_histogram;
for (auto ch : input)
digit_histogram[ch]++;
Then the count of any digit dig is available as digit_histogram[dig]. You can loop through the map, or loop from 0-9 and discard any that is > 3.
This works for any number of digits, and it's 5 lines long without error checking. The point of programming is to make the computer do the work for you ;)
Start with some tests. This helps you understand your requirements, and clarifies your interface and how the function will be called. As this isn't a tutorial on unit testing, I'll just write a simple program that checks all the test cases succeed:
#include <cstdlib>
int main()
{
// these should all return true
if (!validate("41124535")) return EXIT_FAILURE;
if (!validate("13134113")) return EXIT_FAILURE;
if (!validate("24255411")) return EXIT_FAILURE;
// these should all return false
if (validate("34233332")) return EXIT_FAILURE;
if (validate("31111412")) return EXIT_FAILURE;
if (validate("55551122")) return EXIT_FAILURE;
return EXIT_SUCCESS;
}
Obviously this won't compile, as you haven't declared validate(). So let's add it, before main():
#include <string>
bool validate(const std::string& s)
{
return true;
}
It now compiles, but of course it fails because it never returns false. Now we can code the solution. We can count the occurrences of each character with a std::map:
#include <map>
#include <string>
static const int max_repeats = 3;
bool validate(const std::string& s)
{
std::map<char,int> counts;
for (char c: s)
if (++counts[c] > max_repeats)
return false;
return true;
}
Now, this runs, but it fails on the second test (found by commenting out this test and observing a pass - a real unit-test framework would identify the failing test for you).
The failing test has four 1s in it, so it fails. Why was it suppose to succeed? Ah, perhaps we've misinterpreted the requirement! Perhaps it's intended that the string have no more than three consecutive identical characters? Well we can do that too, by keeping count of the most recently seen character and how many repeats.
#include <string>
static const int max_repeats = 3;
bool validate(const std::string& s)
{
char last_seen = 0;
int repeats = 0;
for (char c: s) {
if (c != last_seen) {
// reset the matcher
last_seen = c;
repeats = 1;
} else {
// have we seen too many?
if (++repeats > max_repeats)
return false;
}
}
return true;
}
There are a few things to clean up, such as test cases with exactly three consecutive identical characters, and (perhaps) you might want to validate the length of the argument string.
And you can then convert it into a full program:
#include <iostream>
int main(int argc, char **argv)
{
while (*++argv)
std::cout << *argv << (validate(*argv) ? " OK" : " FAIL") << std::endl;
}

Checking cin input stream produces an integer

I was typing this and it asks the user to input two integers which will then become variables. From there it will carry out simple operations.
How do I get the computer to check if what is entered is an integer or not? And if not, ask the user to type an integer in. For example: if someone inputs "a" instead of 2, then it will tell them to reenter a number.
Thanks
#include <iostream>
using namespace std;
int main ()
{
int firstvariable;
int secondvariable;
float float1;
float float2;
cout << "Please enter two integers and then press Enter:" << endl;
cin >> firstvariable;
cin >> secondvariable;
cout << "Time for some simple mathematical operations:\n" << endl;
cout << "The sum:\n " << firstvariable << "+" << secondvariable
<<"="<< firstvariable + secondvariable << "\n " << endl;
}
You can check like this:
int x;
cin >> x;
if (cin.fail()) {
//Not an int.
}
Furthermore, you can continue to get input until you get an int via:
#include <iostream>
int main() {
int x;
std::cin >> x;
while(std::cin.fail()) {
std::cout << "Error" << std::endl;
std::cin.clear();
std::cin.ignore(256,'\n');
std::cin >> x;
}
std::cout << x << std::endl;
return 0;
}
EDIT: To address the comment below regarding input like 10abc, one could modify the loop to accept a string as an input. Then check the string for any character not a number and handle that situation accordingly. One needs not clear/ignore the input stream in that situation. Verifying the string is just numbers, convert the string back to an integer. I mean, this was just off the cuff. There might be a better way. This won't work if you're accepting floats/doubles (would have to add '.' in the search string).
#include <iostream>
#include <string>
int main() {
std::string theInput;
int inputAsInt;
std::getline(std::cin, theInput);
while(std::cin.fail() || std::cin.eof() || theInput.find_first_not_of("0123456789") != std::string::npos) {
std::cout << "Error" << std::endl;
if( theInput.find_first_not_of("0123456789") == std::string::npos) {
std::cin.clear();
std::cin.ignore(256,'\n');
}
std::getline(std::cin, theInput);
}
std::string::size_type st;
inputAsInt = std::stoi(theInput,&st);
std::cout << inputAsInt << std::endl;
return 0;
}
Heh, this is an old question that could use a better answer.
User input should be obtained as a string and then attempt-converted to the data type you desire. Conveniently, this also allows you to answer questions like “what type of data is my input?”
Here is a function I use a lot. Other options exist, such as in Boost, but the basic premise is the same: attempt to perform the string→type conversion and observe the success or failure:
template <typename T>
auto string_to( const std::string & s )
{
T value;
std::istringstream ss( s );
return ((ss >> value) and (ss >> std::ws).eof()) // attempt the conversion
? value // success
: std::optional<T> { }; // failure
}
Using the optional type is just one way. You could also throw an exception or return a default value on failure. Whatever works for your situation.
Here is an example of using it:
int n;
std::cout << "n? ";
{
std::string s;
getline( std::cin, s );
auto x = string_to <int> ( s );
if (!x) return complain();
n = *x;
}
std::cout << "Multiply that by seven to get " << (7 * n) << ".\n";
limitations and type identification
In order for this to work, of course, there must exist a method to unambiguously extract your data type from a stream. This is the natural order of things in C++ — that is, business as usual. So no surprises here.
The next caveat is that some types subsume others. For example, if you are trying to distinguish between int and double, check for int first, since anything that converts to an int is also a double.
There is a function in c called isdigit(). That will suit you just fine. Example:
int var1 = 'h';
int var2 = '2';
if( isdigit(var1) )
{
printf("var1 = |%c| is a digit\n", var1 );
}
else
{
printf("var1 = |%c| is not a digit\n", var1 );
}
if( isdigit(var2) )
{
printf("var2 = |%c| is a digit\n", var2 );
}
else
{
printf("var2 = |%c| is not a digit\n", var2 );
}
From here
If istream fails to insert, it will set the fail bit.
int i = 0;
std::cin >> i; // type a and press enter
if (std::cin.fail())
{
std::cout << "I failed, try again ..." << std::endl
std::cin.clear(); // reset the failed state
}
You can set this up in a do-while loop to get the correct type (int in this case) propertly inserted.
For more information: http://augustcouncil.com/~tgibson/tutorial/iotips.html#directly
You can use the variables name itself to check if a value is an integer.
for example:
#include <iostream>
using namespace std;
int main (){
int firstvariable;
int secondvariable;
float float1;
float float2;
cout << "Please enter two integers and then press Enter:" << endl;
cin >> firstvariable;
cin >> secondvariable;
if(firstvariable && secondvariable){
cout << "Time for some simple mathematical operations:\n" << endl;
cout << "The sum:\n " << firstvariable << "+" << secondvariable
<<"="<< firstvariable + secondvariable << "\n " << endl;
}else{
cout << "\n[ERROR\tINVALID INPUT]\n";
return 1;
}
return 0;
}
I prefer to use <limits> to check for an int until it is passed.
#include <iostream>
#include <limits> //std::numeric_limits
using std::cout, std::endl, std::cin;
int main() {
int num;
while(!(cin >> num)){ //check the Input format for integer the right way
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << "Invalid input. Reenter the number: ";
};
cout << "output= " << num << endl;
return 0;
}
Under C++11 and later, I have the found the std::stoi function very useful for this task. stoi throws an invalid_argument exception if conversion cannot be performed. This can be caught and handled as shown in the demo function 'getIntegerValue' below.
The stoi function has a second parameter 'idx' that indicates the position of the first character in the string after the number. We can use the value in idx to check against the string length and ascertain if there are any characters in the input other than the number. This helps eliminate input like 10abc or a decimal value.
The only case where this approach fails is when there is trailing white space after the number in the input, that is, the user enters a lot of spaces after inputting the number. To handle such a case, you could rtrim the input string as described in this post.
#include <iostream>
#include <string>
bool getIntegerValue(int &value);
int main(){
int value{};
bool valid{};
while(!valid){
std::cout << "Enter integer value: ";
valid = getIntegerValue(value);
if (!valid)
std::cout << "Invalid integer value! Please try again.\n" << std::endl;
}
std::cout << "You entered: " << value << std::endl;
return 0;
}
// Returns true if integer is read from standard input
bool getIntegerValue(int &value){
bool isInputValid{};
int valueFromString{};
size_t index{};
std::string userInput;
std::getline(std::cin, userInput);
try {
//stoi throws an invalid_argument exception if userInput cannot be
//converted to an integer.
valueFromString = std::stoi(userInput, &index);
//index being different than length of string implies additional
//characters in input that could not be converted to an integer.
//This is to handle inputs like 10str or decimal values like 10.12
if(index == userInput.length()) isInputValid = true;
}
catch (const std::invalid_argument &arg) {
; //you could show an invalid argument message here.
}
if (isInputValid) value = valueFromString;
return isInputValid;
}
You could use :
int a = 12;
if (a>0 || a<0){
cout << "Your text"<<endl;
}
I'm pretty sure it works.