« first day (166 days earlier)      last day (2705 days later) » 

9:38 PM
Hello, i want to create a if case to determine my input type.
This is what i did.
 string name;
    int age;
    cin >> name;
    cin >> age;
    if(typeid(name).name() == "int")
    {
        cout << "int first!";
    }
what i actually want to do is that the order of the input should be irrelevant
this is my second attempt:
string name;
    int age;
    string all;
    getline(cin, all);
    stringstream ss(all);
    cout << ss.str() << endl;;
    ss >> name;
    if(ss.fail())
    {
        ss >> age;
        ss.clear();
        ss >> name;
    }
    cout << name << endl;
    cout << age << endl;
    return 0;
 
10:03 PM
@Schbabako reading to string doesn't fail
 
yes
i thought about it. String can hold anything. So name would also store numbers
So i thought about a conversion to check if it can be converted to int
stoi the first one of ss and look if its int
 
yes, try checking for the number first
 
can i access the first variable in ss or do i have to write it into a new variable?
stoi(ss) obviously will faill :D
 
note that you still need to handle the case when the user provides two numbers
@Schbabako stringstream is irrelevant now once you use std::stoi
 
thats right
 
10:22 PM
How can i catch the error when i try to convert string to int with stoi?
its not just 0
as return value
 
by catching an exception
 
yeah but is there really not any easier way to distinguish inputs?
string name;
    int age;

    cin >> name;
    try{

        if(stoi(name))
        {
            age = stoi(name);
        }
        throw 1;
    }
    catch(int e) {
        cout << name;
    }
    cin >> name;
    cout << name;
    cout << age ;
    return 0;
}
i think i misunderstood somehting
 
11:15 PM
string name;
    int age;

    cin >> name;
    cout << name;

    cin >> age ;
    if(cin.good() == 0)
    {
        cout << "please enter age";
        cin >> age;
    }
    cout << age;
    cout << name;
    return 0;
i found this easier method. I use cin.good to catch that exception.
 

« first day (166 days earlier)      last day (2705 days later) »