阅读量:78
std::stringstream 是 C++ 标准库中的一个类,用于处理字符串流
- 检查状态位:在使用
std::stringstream时,可以通过检查其状态位来判断操作是否成功。例如,可以使用fail()、bad()和eof()方法来检查流的状态。这些方法返回true表示发生了错误,返回false表示操作成功。
#include
#include
#include
int main() {
std::stringstream ss("123 abc");
int num;
ss >> num;
if (ss.fail()) {
std::cerr << "Error: Failed to read an integer from the stream."<< std class="hljs-keyword">else {
std::cout << "Read the number: "<< num class="hljs-keyword">return 0;
}
- 清除错误状态:如果需要在发生错误后继续使用
std::stringstream,可以使用clear()方法清除错误状态。
#include
#include
#include
int main() {
std::stringstream ss("123 abc");
int num;
ss >> num;
if (ss.fail()) {
std::cerr << "Error: Failed to read an integer from the stream."<< std class="hljs-built_in">clear(); // Clear the error state
}
std::string str;
ss >> str;
std::cout << "Read the string: "<< str class="hljs-keyword">return 0;
}
- 异常处理:虽然
std::stringstream默认不会抛出异常,但你可以通过设置异常掩码来改变这种行为。使用exceptions()方法可以设置异常掩码,当指定的条件发生时,将抛出std::ios_base::failure异常。
#include
#include
#include
int main() {
std::stringstream ss("123 abc");
ss.exceptions(std::ios::failbit | std::ios::badbit); // Enable exceptions for failbit and badbit
try {
int num;
ss >> num;
std::cout << "Read the number: "<< num class="hljs-built_in">catch (const std::ios_base::failure& e) {
std::cerr << "Error: " << e class="hljs-built_in">what()<< std class="hljs-keyword">return 0;
}
请注意,异常处理可能会导致性能下降,因此在关注性能的场景中,建议使用状态位检查而非异常处理。