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

Recommended Answers

All 2 Replies

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;
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.