阅读量:148
stringstream 是 C++ 中的一个类,它位于 头文件中。这个类允许你使用流操作符 << 和 >> 来读取和写入字符串。在处理异常情况时,stringstream 可以帮助你以结构化的方式解析字符串。
以下是一些使用 stringstream 处理异常情况的示例:
- 检查读取操作是否成功:
当你使用
>>操作符从stringstream中读取数据时,如果读取失败,该操作符会设置failbit。你可以使用fail()成员函数来检查是否设置了failbit。
#include
#include
#include
int main() {
std::stringstream ss("123 456 789");
int a, b, c;
ss >> a >> b >> c;
if (ss.fail()) {
std::cerr << "读取失败!" << std class="hljs-keyword">else {
std::cout << "读取成功: a="<< a class="hljs-string">", b="<< b class="hljs-string">", c="<< c class="hljs-keyword">return 0;
}
- 处理非数字字符:
如果你尝试从
stringstream中读取一个不存在的值,>>操作符会设置failbit。你可以使用ignore()成员函数来忽略无效字符,并继续读取。
#include
#include
#include
int main() {
std::stringstream ss("abc 123 def 456");
int a, b;
std::string s;
ss >> s >> a; // 读取字符串 "abc" 和整数 123
ss.ignore(std::numeric_limits::max(), ' '); // 忽略空格
ss >> b; // 读取整数 456
if (ss.fail()) {
std::cerr << "读取失败!" << std class="hljs-keyword">else {
std::cout << "读取成功: a="<< a class="hljs-string">", b="<< b class="hljs-keyword">return 0;
}
- 自定义错误处理:
你可以通过重载
<<和>>操作符来自定义错误处理逻辑。例如,你可以为stringstream类创建一个自定义的派生类,并在其中实现自己的错误处理机制。
#include
#include
#include
class MyStream : public std::stringstream {
public:
using std::stringstream::operator>>;
void checkError() {
if (fail()) {
throw std::runtime_error("读取失败!");
}
}
};
int main() {
MyStream ss("123 456 789");
int a, b, c;
ss >> a >> b >> c;
ss.checkError();
std::cout << "读取成功: a="<< a class="hljs-string">", b="<< b class="hljs-string">", c="<< c class="hljs-keyword">return 0;
}
在这个示例中,我们创建了一个名为 MyStream 的自定义类,它继承自 std::stringstream。我们重载了 >> 操作符,并在其中调用了 checkError() 函数来检查是否发生了读取错误。如果发生错误,我们抛出一个 std::runtime_error 异常。在主函数中,我们使用 try-catch 块来捕获并处理这个异常。