Does C++ Console apps have a TryParse equivalent.. I mean .Net has it for both C# and C++ but why does C++ Consoles NOT have this! Or am I just wrong and cannot find it?

I was thinking of writing my own with templates that can be use for ANY type but I'm not sure how I would check if the values are 'parse-able' or not and then to reset the variable upon fail I guess that's where I'd catch an exception :S

Edited by triumphost

6 Years
Discussion Span
Last Post by m4ster_r0shi

Well, Dot Net C++ Console apps also have it, if that's not what you meant.

For standard C++, you would need to write your own function to do that.


I'm not sure how I would check if the values are 'parse-able' or not

You could use a stringstream for that. First, get rid of the trailing whitespace characters in your input. Then, create a stringstream out of your input and use it to set your variable's value. If the operation succeeds and there is no data left in your stringstream object, you're OK.

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

template <class T>
bool TryParse(string input, T & var)
    static const string ws(" \t\f\v\n\r");

    size_t pos = input.find_last_not_of(ws);

    if (pos != string::npos)
        input.erase(pos + 1);
    else input.clear();

    stringstream buffer(input);

    return buffer >> var && buffer.eof();

int main()
    string input;

    int n;
    double d;

    while (cin) // CTRL-Z (or CTRL-D) and enter to quit
        cout << "enter int: "; getline(cin, input);
        if (TryParse(input, n))
            cout << "you entered: " << n << endl;
        else cout << "error" << endl;

        cout << "enter double: "; getline(cin, input);
        if (TryParse(input, d))
            cout << "you entered: " << d << endl;
        else cout << "error" << endl;

Edited by m4ster_r0shi

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.