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