c++

streamstring在c++中的错误处理机制

小樊
82
2024-09-13 01:47:26
栏目: 编程语言

std::stringstream 是 C++ 标准库中的一个类,用于处理字符串流

  1. 检查状态位:在使用 std::stringstream 时,可以通过检查其状态位来判断操作是否成功。例如,可以使用 fail()bad()eof() 方法来检查流的状态。这些方法返回 true 表示发生了错误,返回 false 表示操作成功。
#include<iostream>
#include <sstream>
#include<string>

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::endl;
    } else {
        std::cout << "Read the number: "<< num<< std::endl;
    }

    return 0;
}
  1. 清除错误状态:如果需要在发生错误后继续使用 std::stringstream,可以使用 clear() 方法清除错误状态。
#include<iostream>
#include <sstream>
#include<string>

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::endl;
        ss.clear(); // Clear the error state
    }

    std::string str;
    ss >> str;
    std::cout << "Read the string: "<< str<< std::endl;

    return 0;
}
  1. 异常处理:虽然 std::stringstream 默认不会抛出异常,但你可以通过设置异常掩码来改变这种行为。使用 exceptions() 方法可以设置异常掩码,当指定的条件发生时,将抛出 std::ios_base::failure 异常。
#include<iostream>
#include <sstream>
#include<string>

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<< std::endl;
    } catch (const std::ios_base::failure& e) {
        std::cerr << "Error: " << e.what()<< std::endl;
    }

    return 0;
}

请注意,异常处理可能会导致性能下降,因此在关注性能的场景中,建议使用状态位检查而非异常处理。

0
看了该问题的人还看了