johnyak
johnyak

Reputation: 31

handling stringstream errors with try/catch

How can I handle the following exception without using if/else ( only using try/catch):-

string S;
cin >> S;
stringstream ss(S);
int n;         
try {
   ss>>n;
   if(ss.fail()) throw (exception())
   else cout<<n;
} 
catch (const exception& e) { cout << "Bad String"<<endl;}

Upvotes: 0

Views: 1588

Answers (1)

Jerry Coffin
Jerry Coffin

Reputation: 490663

A stream has an exceptions member function to tell it what condidions should throw exceptions. In this case, you just tell it to throw an exception on fail:

#include <string>
#include <iostream>
#include <sstream>
using namespace std;

int main()
{

    string S;
    cin >> S;
    stringstream ss(S);
    ss.exceptions(ios::failbit);

    int n;
    try {
        ss>>n;
        cout<<n;
    } 
    catch (const exception& e) { 
        cout << "Bad String\n";
    }
}

This turns out to be less useful that it might initially seem, but if that's what you want, this is how you do it.

Oh, and stop using using namespace std;. It's fraught with problems.

Upvotes: 1

Related Questions