阅读量:123
std::stringstream 是 C++ 标准库中的一个类,用于处理字符串流
- 检查状态:在操作
std::stringstream对象时,可以使用fail()、bad()和eof()方法来检查流的状态。例如:
#include
#include
#include
int main() {
std::stringstream ss;
int value;
ss << "Not a number";
ss >> value;
if (ss.fail()) {
std::cerr << "Failed to read an integer from the stream."<< std class="hljs-keyword">return 0;
}
- 清除状态:如果需要继续使用同一个
std::stringstream对象,可以使用clear()方法清除流的状态。例如:
#include
#include
#include
int main() {
std::stringstream ss;
int value;
ss << "Not a number";
ss >> value;
if (ss.fail()) {
std::cerr << "Failed to read an integer from the stream."<< std class="hljs-built_in">clear(); // Clear the error state
ss.ignore(std::numeric_limits::max(), '\n'); // Ignore the rest of the input
ss.str(""); // Clear the contents of the stream
}
// Now the stringstream is ready for new input
ss << "42";
ss >> value;
std::cout << "Read value: "<< value class="hljs-keyword">return 0;
}
- 异常处理:虽然
std::stringstream不会抛出异常,但你可以设置流的异常掩码,以便在特定条件下抛出异常。例如:
#include
#include
#include
int main() {
std::stringstream ss;
int value;
ss.exceptions(std::ios::failbit | std::ios::badbit); // Enable exceptions for failbit and badbit
try {
ss << "Not a number";
ss >> value;
} catch (const std::ios_base::failure& e) {
std::cerr << "An exception occurred: " << e class="hljs-built_in">what()<< std class="hljs-keyword">return 0;
}
请注意,std::stringstream 不会因为遇到无效输入而抛出异常,除非你显式地设置了异常掩码。在大多数情况下,检查流的状态并根据需要清除错误状态是更好的做法。