allow the user to skip entering one of the values

can someone give me an example of a code that will still run if the user don't input a data? like for example if the user has to put 2 numbers, and the user skipped the first one, it will skip to the 2nd one.
I haven't tested this but it should be close to what you asked. Remember to default x and y to something or check ignore *every single time* you were going to use either x or y in the code. I recommend a harmless default.

bool ignore = false;
string s;
cin >> s;
int x,y;

try
{
x = stoi(s);
}
catch (const std::invalid_argument& ia)
{
ignore = true;
}
if(!ignore)
{
cin >> s;
y = stoi(s); // you may as well check this one too.
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

int main()
{
    int first = 10 ; // 10 is the default value for first
    std::cout << "first number (press enter to skip): " ;
    if( std::cin.peek() != '\n' ) std::cin >> first ;

    std::cin.ignore( 1000, '\n' ) ; // extract and discard the new line

    int second = 25 ; // 25 is the default value for second
    std::cout << "second number (press enter to skip): " ;
    if( std::cin.peek() != '\n' ) std::cin >> second ;

    std::cout << "first: " << first << "  second: " << second << '\n' ;
}
Topic archived. No new replies allowed.