简体   繁体   English

使用try / catch处理stringstream错误

[英]handling stringstream errors with try/catch

How can I handle the following exception without using if/else ( only using try/catch):- 在不使用if / else的情况下如何处理以下异常(仅使用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;}

A stream has an exceptions member function to tell it what condidions should throw exceptions. 一个流有一个exceptions成员函数来告诉它什么条件应该抛出异常。 In this case, you just tell it to throw an exception on fail : 在这种情况下,您只需告诉它在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; 哦,停止using namespace std; . It's fraught with problems. 它充满了问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM