Please be nice I am a total newby.
I have a list of variables (strings) from num1 to num90. I need to call these from a function by adding the number in an int to the word num.
The task is to convert digits to words from 'jumping into c++'...I might not be going about it in the 'right' way but this part has been stopping me for a while now!!
I'm trying like this:
#include <iostream>
#include <string>
using namespace std;
// Hard code numbers to 20 and then in tens to 90
string num1 = "one";
string num2 = "two";
string num3 = "three";
string num4 = "four";
string num5 = "five";
string num6 = "six";
string num7 = "seven";
string num8 = "eight";
string num9 = "nine";
Etc...up to 90
int main ()
{
// Break the number down into three digit blocks
int num = 0;
cout << "Please enter the number: ";
cin >> num;
while (num > 999)
{
int digit = (num % 1000);
num = ((num - digit)/1000);
//cout << digit << '\n';
//cout << num << '\n';
// For each block of numbers work out hundreds,
if (digit > 100)
{
int i = digit;
int j = (i % 100);
cout << num.append(j) << " hundred";
}
What I need to happen is the number stored in 'j' to be tagged onto the word num in order to call the string num*.
Is this possible?
Sure, use a map:
#include <map>
#include <string>
#include <iostream>
std::map<int, std::string> words { { 1, "one" }, { 2, "two" }, { 3, "three" } };
int main()
{
std::cout << words[1] << std::endl;
}
You'll probably have to deal with some special cases (up to twenty?), and you need a word for "hundred", etc. If you want to make it internationalizable, you'll have to think even harder.
What I need to happen is the number stored in 'j' to be tagged onto
the word num in order to call the string num*.
The trouble with that approach is that any variable names you use in your code are not compiled: when the program runs it will manipulate the values of your variables, but it doesn't know or care that you decided to use the name "num3" instead of "numero3" or "foobar".
If you want to make a link between a digit (3) and a string ("three") then you can use a Vector (as #Mark suggests, although you'll have problems after 20) or better still a Map (as #Kerrek suggests): these will work because in both cases the strings are referenced by the value of a variable (eg the value of digit in lookup[digit], or the literal value 1 in words[1]) rather than by the name of a variable.
EDIT:
For interest, here's a version using 'if' and 'switch'...
#include <iostream>
#include <string>
using namespace std;
string units2word(int units){
switch (units){
case 0: return "zero";
case 1: return "one";
case 2: return "two";
case 3: return "three";
// etc ...
case 18: return "eighteen";
case 19: return "nineteen";
}
}
string tens2word(int tens){
switch(tens){
case 2: return "twenty";
case 3: return "thirty";
// etc ...
case 9: return "ninety";
}
}
string num2words(int num) {
if (num > 99 && num%100 == 0) return units2word(num/100) + " hundred";
if (num > 99) return units2word(num/100) + " hundred and " + num2words(num%100);
if (num < 20) return units2word(num);
if (num%10 == 0) return tens2word(num/10);
return tens2word(num/10) +"-"+ units2word(num%10);
}
int main(int argc, char *argv[]) {
int num = -1;
while( num < 0 || num > 999){
cout << "Please enter a number between 0 and 999: ";
cin >> num;
}
cout << "You typed: " << num2words(num) << endl;
}
You should look at using std::vector. This gives you a variable that takes an index
std::vector<std::string> lookup;
lookup.push_back( "zero" ); // starts at lookup[0]
lookup.push_back( "one" );
lookup.push_back( "two" );
// etc
// then
std::cout << lookup[digit] << std::endl;
std::cout << lookup[num] << std::endl;
Related
I am so close to solving this roman numeral to integer problem. However, in my if statement for when character equals M, I am getting an error thrown when declaring my previous variable when the input is MCMXCIV for example. Because there is nothing before M, it is throwing an out-of-bounds error. How can I fix this?
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
using namespace std;
//Character to search and add to the integer
char character;
//The integer value that is needed to add up and output the corresponding value
int integer = 0;
//One of the test runs and what will be needed for every special case
int main()
{
//Roman numeral given
string input;
//Prompt for user to enter the roman numeral integer
cout << "Enter the roman numeral you want to convert into a number: " << endl;
cin >> input;
cout << input << " is what you are wanting to convert." << endl;
//Read through the string that is being inputted then assign values to the overall integer
for (int i = 0; i < input.length(); i++)
{
character = input.at(i);
cout << "This is the character that is being read right now: " << character << endl;
//Arithmitic for when the character is found and the corresponding value needs to be added
if(character == 'I')
{
integer+=1;
cout << "Integer value now: " << integer << endl;
}
else if(character == 'V')
{
char previous = input.at(i-1);
integer+=5;
if(character == 'V' && previous == 'I')
{
integer = integer - 2;
}
cout << "Integer value now: " << integer << endl;
}
else if(character == 'X')
{
integer+=10;
cout << "Integer value now: " << integer << endl;
}
else if(character == 'L')
{
integer+=50;
cout << "Integer value now: " << integer << endl;
}
else if(character == 'C')
{
integer+=100;
cout << "Integer value now: " << integer << endl;
}
else if(character == 'D')
{
integer+=500;
cout << "Integer value now: " << integer << endl;
}
else if(character == 'M')
{
char previous = input.at(i-1);
integer+=1000;
if(character == 'M' && previous == 'C')
{
integer -= 200;
}
cout << "Integer value now: " << integer << endl;
}
}
cout << "The integer value is: " << integer << endl;
}
First of all: Good that you used the at() function. So you could detect the "out of bounds" problem.
in char previous = input.at(i - 1);, variable "i" could be 0 and you then try to access array element "-1", which is of course out of bounds for your use case.
So, you need an additional check, if "i" greater then 0, before subtracting.
But in general, your approach is too complicated. You can make your life easier, by analyzing or reading, how roman numerals are defined. Look for example here. And please read especially about the "subtractive notation".
You already noticed that but, unfortunately, your implementation is not always following that rule. You made the check only for "M" and "V". But basically, you need to do that for all literals (except "I").
You can boil down this to the rule:
If a literal before a following literal is less, then use the subtrative form. Or, even better, you can read from right to left and finally say:
"If the current literal is less than the follwoing, then use the subtractive form."
And what is the subtractive form? We can simply add the negative number. Example, using number 94 which is "XCIV". We start summing up from the right:
Start. Begin from right. Initialize sum with rightmost value: Looking at 'V': sum = 5
Next: Read 'I'. Check, if this is less than the following literal 'V'. Yes, it is. So, use subtractive form. Add the negative. Now sum = sum + (-1), sum = 4
Now: Read 'C'. Check, if this is less than the following literal 'I'. No, it is not. So, simply add the positive value. Now sum = sum + 100, sum = 104
Next: Read 'X'. Check, if this is less than the following literal 'C' . Yes, it is. So, use subtractive form. Add the negative. Now sum = sum + (-10), sum = 94
So, this is now a very simply algorithm. We will convert a roman literal (one letter) to a integer and then build a sum with positive or negative values.
One of many many potential implementations could look like this:
#include <iostream>
#include <string>
int convert(char romanLiteral) {
switch (romanLiteral) {
case 'I':
return 1;
case 'V':
return 5;
case 'X':
return 10;
case 'L':
return 50;
case 'C':
return 100;
case 'D':
return 500;
case 'M':
return 1000;
default:
return 0;
}
}
int romanLiteralStringToInteger(const std::string& romanLiteralString) {
// Sanity check:
if (romanLiteralString.empty()) return 0;
// Get length of input string
int lengthOfRomanLiteralString = static_cast<int>(romanLiteralString.length());
// Initialize sum with rightmost value
int sum = convert(romanLiteralString[lengthOfRomanLiteralString-1]);
// Now iterate over the string form right to left
for (int i = lengthOfRomanLiteralString - 2; i >= 0; --i) {
// Check if this literal is less than the following
if (convert(romanLiteralString[i]) < convert(romanLiteralString[i+1]))
sum -= convert(romanLiteralString[i]);
else
sum += convert(romanLiteralString[i]);
}
return sum;
}
int main() {
std::string romanNumber = "XCIV";
std::cout << romanNumber << " --> " << romanLiteralStringToInteger(romanNumber) << '\n';
}
In C++ you would probably use associative containers like std::map or std::unordered_map for converting one literal to a number. And maybe a ternary operator, instead of an if.
Then the problem could be implemented like the following:
#include <iostream>
#include <string>
#include <unordered_map>
int romanLiteralStringToInteger(const std::string& romanLiteralString) {
if (romanLiteralString.empty()) return 0;
std::unordered_map<char, int> T = { { 'I' , 1 }, { 'V' , 5 }, { 'X' , 10 }, { 'L' , 50 }, { 'C' , 100 }, { 'D' , 500 }, { 'M' , 1000 } };
int sum = T[romanLiteralString.back()];
for (int i = romanLiteralString.length() - 2; i >= 0; --i)
sum += (T[romanLiteralString[i]] < T[romanLiteralString[i + 1]] ? -T[romanLiteralString[i]] : T[romanLiteralString[i]]);
return sum;
}
int main() {
std::string romanNumber = "XCIV";
std::cout << romanNumber << " --> " << romanLiteralStringToInteger(romanNumber) << '\n';
}
And the hardcore solution with a stateful lambda.
#include <iostream>
#include <string>
#include <unordered_map>
#include <numeric>
#include <iterator>
std::unordered_map<char, int> ARTI{{'I',1 },{'V',5 },{'X',10 },{'L',50 },{'C',100},{'D',500 },{'M',1000 }};
int main() {
std::string romanNumber = "XCIV";
std::cout << std::accumulate(std::next(romanNumber.rbegin()), romanNumber.rend(), ARTI[romanNumber.back()], [&, next = ARTI[romanNumber.back()]](const int s, const char c) mutable {
int sum = s + (ARTI[c] < next ? -ARTI[c] : ARTI[c]); next = ARTI[c]; return sum; });
}
So this is my code:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
long int iterFunc(int);
long int recurFunc(int);
int main() {
int n;
while(true){
try{
cout << "Enter: ";
if (!(cin >> n))
throw("Type Error");
if (n < 0)
throw n;
else
if (n == 0)
break;
cout << "Iterative: " << iterFunc(n) << endl;
cout << "Recursive: " << recurFunc(n) << endl;
}
catch(int n){
cout << "Error. Enter positive number." << endl;
}
catch(...){
cin.clear();
cin.ignore(100, '\n');
cout << "Error. Please enter a number" << endl;
}
}
cout << "Goodbye!";
return 0;
}
long int iterFunc(int n){
vector<long int> yVec = {1, 1, 1, 3, 5};
if (n <= 5)
return yVec[n - 1];
else
for(int i = 5;i < n; i++){
long int result = yVec[i - 1] + 3 * yVec[i- 5];
yVec.push_back(result);
}
return yVec.back();
}
long int recurFunc(int n){
switch (n) {
case 1:
case 2:
case 3:
return 1;
break;
case 4:
return 3;
break;
case 5:
return 5;
break;
default:
return recurFunc(n - 1) + 3 * recurFunc(n - 5);
break;
}
}`
The program shoud accept only one integer and return the y of the function using both iterative and recursive implemetations. Ex.: 30, 59, 433. How can I throw an error message if the user enters more then one integer, separated by space? Ex.: '3 45 32'.
I tried using if (cin.getline == ' ') throw("Error name") but the program still executes and return the y of the function for number in the input
Something like this works:
int main()
{
std::string str;
std::cout << "? : ";
std::getline(std::cin, str);
std::string::size_type pos(0);
int i = std::stoi(str, &pos);
if (pos != str.length())
return 1;
}
I found a part of my old code that might come in handy.
int val;
do
{
cin>>val;
if(!cin){ //you can add more conditions here
cin.clear();
cin.sync();
/* additional error handling */
}
else{
break; //input is correct - leaving loop
}
}while(true); //or here
Basically what !cin does is - it checks what type of value you actually want to write to, because it's needed anyway to figure out if data type is written to the correct type of our val. This means, that "30" or "433" etc. are integers (correct), "s" or "string" etc. are strings (or char*, correct me if I am wrong) (incorrect).
This also means, that "3 45 32" should be interpreted as string, which should result in another loop run.
Note: I didn't really test this code, so it might be completely wrong.
Edit: Okay now after some tests I realised this code needs some retweaking.
Firstly, "3 45 32" is not interpreted as string (now understandable). Instead, first number (before whitespace) is saved as an integer and all other numbers are stored in the buffer (next cin will be filled with it), which we can avoid using cin.clear() and cin.sync() once again.
The question is - is it okay for you to accept the first integer and ignore everything after the first whitespace? If not, you will have to save the input as string and extract whatever data you want from it.
I am leaving the original answer as is for simplicity of finding references in this edit.
This question already has answers here:
Elegant ways to count the frequency of words in a file
(8 answers)
Need a code that counts the same digit in a number
(2 answers)
Closed 5 years ago.
Was trying out a question that I saw online, the questions requires the user to input the number of time the random number will be generated and to count how many digit 1, digit 2, digit 3, are there int he generated number.
For example
Enter number of time to loop : 4
2241 1204 5532 8593
There are 8 digits 1, digit 2 and digit 3.
code:
int main()
{
int input;
int ranNum;
cout << "Enter the number of time to loop" << endl;
cin >> input;
srand(time(NULL));
int i = 0;
if (input < 0 || input > 50)
{
cout << "Invalid entry";
}
else
{
while(i++ < userInput)
{
ranNum = (rand() % 10000);
cout << ranNum<< " ";
}
}
return 0;
}
The questions stated that using a switch case will be easier to get it done. However, I am not too sure how can a switch case worked for this. Or, is there any other method that I can use?
I've completed the code for the first 2 part, which is requiring user to input number as well as generating the random number based on user input
To count the number of occurrences of 1, 2 and 3 in a single integer value it would be easiest IMO to convert the integer into a string and then count the digits you are interested in:
int countDigits(int number, std::string digitsOfInterest = "123") {
int ret = 0;
std::string numberAsString = std::to_string(number); // convert it to string
for (const char& digit : numberAsString) { // loop over every character
if (digitsOfInterest.find(digit) != std::string::npos) {
ret++;
}
}
return ret;
}
Simply pass a randomly generated number into the function and add up the results. As you can see, by changing digitsOfInterest to another string, you can alter the digits you want to count.
PS.: Since I'm assuming that you have access to C++11 I would recommend to change your number generation to <random>.
Here is a non C++11 solution which works the same way the above one does:
int countDigits(int number, std::string digitsOfInterest = "123") {
int ret = 0;
std::ostringstream oss;
oss << number;
std::string numberAsString = oss.str(); // convert it to string
for (size_t i = 0; i < numberAsString.size(); ++i) { // loop over every character
if (digitsOfInterest.find(numberAsString[i]) != std::string::npos) {
ret++;
}
}
return ret;
}
Here is an example:
std::cout << "This number: '1243' contains " << countDigits(1243) << " times a digit of 1,2 or 3\n";
Result: This number: '1243' contains 3 times a digit of 1,2 or 3
I divided it to functions so it will be easier to understand.
I used switch case because that what you asked, but there are other ways as well.
#include<time.h>
#include <iostream>
#include <stdlib.h>
// This function is the UI, i.e. asking the user how many numbers to generate
int HowManyNumbers()
{
int input;
std::cout << "Enter the number of time to loop" << std::endl;
std::cin >> input;
return input;
}
// This function counts 1,2,3 for individual number
int Count123InNum(int num)
{
int count = 0;
while(num)
{
int lastDig = num % 10;
// count only if lastDigit in number is 1,2 or 3
switch(lastDig)
{
case 1:
case 2:
case 3:
++count;
break;
default:
break;
}
num /= 10;
}
return count;
}
// This function receives number of random numbers to generate,
// and its output is a print of the numbers and the joint occurences of 1,2 and 3
void Get123FromRandomNums(int nRandNumbers)
{
srand(time(NULL));
std::cout << "In the numbers: ";
int count = 0;
while(nRandNumbers--)
{
int num = rand() % 10000;
std::cout << num << " ";
count += Count123InNum(num);
}
std::cout << "There are " << count << " digits 1, digit 2, digit 3." << std::endl;
}
int main()
{
// Get number of random numbers (i.e. iterations)
int nRandNumbers = HowManyNumbers();
// check validity
if (nRandNumbers < 0 || nRandNumbers > 50)
{
std::cout << "Invalid entry" << std::endl;
}
else
{
//if valid, count and print 1,2,3 occurences
Get123FromRandomNums(nRandNumbers);
}
return 0;
}
Alright so I've been looking though Google and on forums for hours and can't seem to understand how to solve this problem.
I need to write a program that first determines if the number entered by the user is a base 5 number (in other words, a number that only has 0s, 1s, 2s, 3s, and 4s in it). Then, I have to count how many 0s, 1s, 2s, etc are in the number and display it to the user.
I've seen people saying I should convert int to a string and then using cin.get().
I noticed that I can't use cin.get() on a string, it needs to be a char.
I can only use a while loop for this assignment, no while... do loops.
Any help is appreciated!!
Here's what I have so far, obviously with all my mistakes in it:
//----------------------------------------------
// Assignment 3
// Question 1
// File name: q1.cpp
// Written by: Shawn Rousseau (ID: 7518455)
// For COMP 218 Section EC / Winter 2015
// Concordia University, Montreal, QC
//-----------------------------------------------
// The purpose of this program is to check if the
// number entered by the user is a base of 5
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
// Declaring variables
int number;
int zeros;
int ones;
int twos;
int threes;
int fours;
bool base5;
// Get data and calculate
cin >> number;
string numberString = to_string(number);
// Determine if the number is a base 5 number
while (cin.get(numberString) == 0 || cin.get(numberString) == 1 ||
cin.get(numberString) == 2 || cin.get(numberString) == 3 ||
cin.get(numberString) == 4)
base5 = true;
// Determine the number of each digits
zeros = 0;
ones = 0;
twos = 0;
threes = 0;
fours = 0;
return 0;
}
Several things you need to beware of:
One way to get a specific character from a std::string is by []. e.g.
std::string myString{"abcdefg"};
char myChar = myString[4]; // myChar == 'e'
cin.get(aString) is not trying to get data from aString. It continues to get data from stdin and store in aString. Once you have get the data and put into the string, you can simply manipulate the string itself.
a short piece of code that will count number of vowel in a string. If you can understand it, there should be no problem doing your work. (Haven't compiled, probably some typos)
std::string inputString;
std::cin >> inputString;
// you said you need a while loop.
// although it is easier to with for loop and iterator...
int i = 0;
int noOfVowels = 0;
while (i < inputString.length()) {
if (inputString[i] == 'a'
|| inputString[i] == 'e'
|| inputString[i] == 'i'
|| inputString[i] == 'o'
|| inputString[i] == 'u' ) {
++noOfVowels;
}
++i;
}
std::cout << "number of vowels : " << noOfVowels << std::endl;
Well you can try this approach. This will solve your needs I guess.
#include <iostream>
#include <string>
#include <sstream>
#include <conio.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int number=0;
int zeros=0;
int ones=0;
int twos=0;
int threes=0;
int fours=0;
bool valid=true;;
int counter = 0;
cout<<"Enter the number: ";
cin >> number;
stringstream out;
out << number; //int to string
string numberString = out.str();
cout<<"\n\nNumber after string conversion : "<<numberString;
cout<<"\nPrinting this just to show that the conversion was successful\n\n\n";
while (counter < numberString.length())
{
if (numberString[counter] == '0')
zeros++;
else if(numberString[counter] == '1')
ones++;
else if(numberString[counter] == '2')
twos++;
else if(numberString[counter] == '3')
threes++;
else if(numberString[counter] == '4')
fours++;
else
valid=false;
counter++;
}
if(valid==true)
{
cout<<"\nZeros : "<<zeros;
cout<<"\nOnes : "<<ones;
cout<<"\nTwos : "<<twos;
cout<<"\nThrees : "<<threes;
cout<<"\nFours : "<<fours;
}
else
cout<<"\n\nInvalid data...base of 5 rule violated";
_getch();
return 0;
}
If you don't want to use std::string then use characters, first loop over the input from the user until ENTER is pressed.
char ch = 0;
while ((ch = cin.get()) != '\n')
{
...
}
For each character read, check if it is a digit (std::isdigit) and if it is in the range 0..4, if not quit and give some message of not being base 5
have an array of ints to keep track of the frequency of the digits
int freq[5] = {0,0,0,0,0};
after you have checked that the character is valid subtract the ascii value from the digit and use that as index in the array, increment that:
freq[ch - '0']++;
e.g.
char ch;
int freq[5] = {0};
while ((ch = cin.get()) != '\n')
{
cout << ch;
freq[ch-'0']++;
}
for (int i = 0; i < sizeof(freq)/sizeof(freq[0]); ++i)
{
cout << static_cast<char>(48+i) << ":" << freq[i] << endl;
}
Here's a useful function that counts digits:
// D returns the number of times 'd' appears as a digit of n.
// May not work for n = INT_MIN.
int D(int n, int d) {
// Special case if we're counting zeros of 0.
if (n == 0 && d == 0) return 1;
if (n < 0) n = -n;
int r = 0;
while (n) {
if (n % 10 == d) r++;
n /= 10;
}
return r;
}
In your code you can use this naively to solve the problem without any further loops.
if (D(n, 5) + D(n, 6) + D(n, 7) + D(n, 8) + D(n, 9) != 0) {
cout << "the number doesn't consist only of the digits 0..4."
}
cout << "0s: " << D(n, 0) << "\n";
cout << "1s: " << D(n, 1) << "\n";
cout << "2s: " << D(n, 2) << "\n";
cout << "3s: " << D(n, 3) << "\n";
cout << "4s: " << D(n, 4) << "\n";
You could also (or should also) use loops here to reduce the redundancy.
In my program, I want users to choose between two choices. Simply, 1 or 2. I have written the program to where it will protect against an invalid numeric value such as 3 or 28, but I cannot protect against alphabetical input.
Code is as follows:
int whileInt = 0;
int choiceOne_One = 0;
while(whileInt == 0)
{
cin >> choiceOne_One;
if(choiceOne_One != 1 && choiceOne_One != 2)
{
cout << "Woah! That wasn't an option! Try Again.\n";
}
else if(choiceOne_One == 1)
{
whileInt++;
cout << "\nYou have died. Be more careful.\n";
}
else if(choiceOne_One == 2)
{
whileInt++;
cout << "\nYou have survived the alien invasion due to your cunning sense of "
"safety.\nCongratulations.\n";
}
}
My brain still works in Java, please help me figure this out. It will definitely be appreciated.
Try this :
#include <iostream>
using namespace std;
int main()
{
char input;
cin>>input;
switch(input)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
cout<<"valid input"<<endl;
break;
default :
cout<<"Invalid input"<<endl;
}
return 0;
}
You can define a case for all your valid inputs, leave the rest to default.
Integers from 0-9 have their ASCII values from 48-57 respectively.
This solution wont be helpful if you have
. input>9 or input<0
. input such as 1abc
Might be a bit late but my favorite way to do and this is what i use :
#include <iostream>
#include <string>
#include <limits>
//T is for our variable and lambdaFunc will be our lambda function or
//function pointer
template<typename T, typename lambdaFunc>
auto secureEntry(T& variable, LambdaFunc lFunc, std::string errorMessage) //can ommit error message
{
while(!(std::cin(variable)) && !lFunc(variable)){
std::cout << errorMessage << std::endl;
std::cin.clear();
std::ignore((std::numeric_limits<std::streamsize>::max)(), '\n');
}
}
int main(int argc, char* argv[]){
int mynumber = {0};
std::string errorMessage = "Please use a number bigger than 0 and lower than 5"
secureEntry(myNumber, [](int& mynumber) -> bool{
return mynumber > 0 && mynumber < 5;
}, errorMessage)
}
you can do this also
int whileInt=0;
int choiceOne_One = 0;
while(whileInt == 0)
{
cin >> choiceOne_One;
if (choiceOne_One == 1 || choiceOne_One == 2){
if (choiceOne_One == 1){
whileInt++;
cout << "\nYou have died. Be more careful.\n";
}
else {
whileInt++;
cout << "\nYou have survived the alien invasion due to your cunning sense of "
"safety.\nCongratulations.\n";
}
}
else {
cout << "Woah! That wasn't an option! Try Again.\n";
}
}
Try reading a std::string with std::getline, then simply compare the string with "1" or "2". Otherwise, you can just read the whole line with std::getline, then use std::stoi (C++11) to transform the read string into an integer. The result of std::stoi tells you whether the transformation was successful or not (i.e., whether the string represented an integer). If successful, then you can simply compare the integer with 1 or 2. If not successful, then an std::invalid_argument or std::out_of_range exception is thrown.
First case (with std::string comparison):
#include <iostream>
int main()
{
std::string input;
std::getline(std::cin, input);
if (input != "1" && input != "2")
std::cout << "Invalid input!";
}
Second case (using std::stoi):
#include <iostream>
int main()
{
std::string input;
std::getline(std::cin, input);
int n = std::stoi(input); // throws exception if cannot convert to int
if (n != 1 && n != 2)
std::cout << "Invalid input!";
}
If you change the program so that cin puts a User's answer to a std::string, then you could do tests on the string value.
If the string's length() was more than 1, it cannot be '1' or '2'
There are additional tests you can do, like std::isalpha(int ch)
#include <stdio.h>
#include <string>
#include <iostream>
int main(int argc, char * argv[]) {
std::string value;
std::cin >> value;
std::cout << "Value is " << value << "\n";
std::cout << "length of value is " << value.length() << "\n";
char ch;
ch = value.at(0);
if(std::isalpha(ch)) std::cout << "You did not enter a number" << "\n";
return 0;
}
robert#debian:/tmp$ g++ -Wall test.cpp
robert#debian:/tmp$ ./a.out
123
Value is 123
length of value is 3
robert#debian:/tmp$ ./a.out
abc
Value is abc
length of value is 3
You did not enter a number