I am a newbie at C++ and I got really stuck at this problem:
When the user enters 2 numbers EX: 1 and 2 than the code has to figure out if the first number is grater or not from the first one, the problem is that the code doesn't bring the true or false as text it brings it as numbers :/
(0= false 1=true)
Code here:
#include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
bool GraterFunct(int num1, int num2);
int main(int argc, char** argv)
{
std::cout <<" \n Hello there! This is a test to test how good you are with math. \n ";
std::cout <<" Now enter G or L (Grater, less) to know if a number is grater or less than the number you choose \n ";
char answer [1];
std::cin >> answer;
if(answer == "G" || "g")
{
int number1;
int number2;
std::cout << "You selected: Grater than, \n";
std::cout << "Now type 2 numbers and see which one is grater than the other one. \n" << std::endl;
std::cin >> number1;
std::cout << "Your first number: " << number1 << std::endl;
std::cout << "Select your second number \n";
std::cin >> number2;
std::cout << "The answer is: " << GraterFunct(number1, number2);
}
return 0;
}
bool GraterFunct(int num1, int num2)
{
if(num1 >= num2)
{
{
return true;
}
}
else
{
if(num2 >= num1)
{
return false;
}
}
}
Please help! Thanks in advance!
To format Boolean values as true and false you can set the std::ios_base::boolalpha flag using the std::boolalpha manipulator:
std::cout << std::boolalpha << "true=" << true << " false=" << false << '\n';
In case you are a non-native English speaker like me, you might want to change the formatting of these values. Assuming there are suitable locales installed you can just imbue() into a stream or you can create you own locale with whatever rendering of true and false you want, e.g.:
#include <iostream>
#include <locale>
class numpunct
: public std::numpunct<char>
{
std::string do_truename() const { return "wahr"; }
std::string do_falsename() const { return "falsch"; }
};
int main()
{
std::cout.imbue(std::locale(std::locale(), new numpunct));
std::cout << std::boolalpha << "true=" << true << " false=" << false << '\n';
}
BTW, you always need to verify that you input was successful, e.g.:
if (std::cin >> number1) {
// deal with the successful input here
}
else {
// deal with the wrong input here
}
Related
I need help for looping back on the start of the program [C++].
#include <iostream>
#include <ctime>
using namespace std;
int main(int argc, char *argv[])
{
srand(time(NULL));
int rand_number = rand() % 101;
int number;
int counter = 1;
cout << "NUMBER GUESSING" << endl;
cout << "Try to guess number from 1 to 99: " << endl;
do
{
cout << "Input number: ";
cin >> number;
if (number < rand_number)
{
cout << "Number is too small." << endl;
}
else
{
if (number > rand_number)
{
cout << " Number is too big." << endl;
}
}
number++;
} while (number != rand_number);
cout << "Great! You guessed it in " << number << "th try." << endl;
cout << "Do you want to play again [Y/N]: ";
cin >> Y;
cin >> N;
// dont know how to proceed
return 0;
}
I need help for looping back on the start when it asks me if I want to play again and answer Yes "Y", if I answer No "N" it says Goodbye. Any help would be appreciated, Thanks.
Similar to how you are using a do while, try adding an outer while loop that checks if the N key was pressed
You could create a boolean playAgain which would start as true. If the player says no, set it to false. You can then put your do while in another do while(playAgain). This would loop the game until the player says he does not want to play again.
It is not the most orthodox method but it works :) Use goto.
int main()
{
mylabel:
...
if( <condition> )
{
goto mylabel;
}
...
}
If you want to have a more structured program write your main in anther function, say int func() and loop in main based on the return of the function.
int func()
{
...
if( <condition> )
{
return 1;
}
...
return 0;
}
int main()
{
while(func())
{};
return 0;
}
A very easy way to do this is to use nested while loops. You can use what you already have as the inner loop, then have another outside that that checks if the user has put in a Y or not. It can look something like this:
do {
do {
//Get numbers and check them
//...
} while(number != rand_number);
std::cout << "Some message" << std::endl;
std::cin >> option;
} while(option != 'N');
This goes through your loop, then allows the user to choose to continue. If they choose to go again, it will take them back up to the top of the outer while loop, and keep going until they say to stop.
EDIT:
Here would be the complete code:
#include <iostream>
#include <ctime>
using namespace std;
int main(int argc, char *argv[])
{
srand(time(NULL));
char option = 'a';
do
{
int rand_number = rand() % 101;
int number;
int counter = 1;
std::cout << "NUMBER GUESSING" << std::endl;
std::cout << "Try to guess number from 1 to 99: " << std::endl;
do
{
std::cout << "Input number: ";
std::cin >> number;
if (number < rand_number)
{
std::cout << "Number is too small." << std::endl;
}
else if (number > rand_number)
{
std::cout << " Number is too big." << std::endl;
}
counter++;
} while (number != rand_number);
std::cout << "Great! You guessed it in " << counter << "th try." << std::endl;
std::cout << "Do you want to play again [Y/N]: ";
std::cin >> option;
} while(option !='N');
std::cout << "Goodbye!" << std::endl;
return 0;
}
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.
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;
}
I have a question that might be very simple to many of you however, I have not found an answer to my question.
I have the program below that is working properly. This code turns a number into a floating number and integer.
Let's say you entered 5.4, the program will give you 5.4 for double and 5 for integer.
Now I need to add a throw catch statement to my program in case the user enters a text instead of a number ("If the conversion fails, throw an exception and allow the user to re-enter the value.").
This is the pseudocode of what I need to do.
try {
if(num ==character)
throw;
cout << "\n The number entered " << num << "invalid, please enter again";
}
catch
{
}
and I implemented something like this, however it did not work. I set the 'a' variable character thinking the user has to enter a text in order to get that message. However it did not work and gave some errors.
try
{
char a;
if (num == a)
throw num;
}
catch(int e)
{
cout << "A number of " << a << " is invalid." << endl;
cout << "Please re-enter a number: ";
cin << num
}
I am very new with this "try,throw,catch" terms. I would be happy if you help me through this, thanks.
#include <C:\\CSIS1600\MyCppUtils.cpp>
#include <iostream>
#include <string>
using namespace myNameSpace;
int main()
{
runner("is running");
cout << "Enter a number : ";
string num;
getline(cin, num);
cout<< "double " << getValidDouble(num) << endl;
cout<< "integer " << getValidInt(num) << endl;
system("pause");
return 0;
}
#include<iostream>
#include<string>
using namespace std;
namespace myNameSpace
{
string num;
void runner(string str)
{
cout <<"runner-3() is running.."<<endl;
}
int getValidInt(string n)
{
int valueint;
valueint=atoi(n.c_str());
return valueint;
}
double getValidDouble(string n )
{
double valuedouble;
valuedouble = atof(n.c_str());
return valuedouble;
}
}
You can use Boost to do a lexical cast. If you have valid input (e.g. 2.54), no exception will be thrown, but with invalid input (e.g. 2???54) the bad_lexical cast is thrown:
#include <boost/lexical_cast.hpp>
try
{
double x1 = boost::lexical_cast<double> ("2.54");
double x2 = boost::lexical_cast<double> ("2???54");
cout << x1 << x2 << endl;
}
catch(boost::bad_lexical_cast& e)
{
cout << "Exception caught - " << e.what() << endl;
}
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.