stringstream

stringstream在异常情况下的处理

小樊
86
2024-09-03 15:30:48
栏目: 编程语言

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

  1. 检查状态:在操作 std::stringstream 对象时,可以使用 fail()bad()eof() 方法来检查流的状态。例如:
#include<iostream>
#include <sstream>
#include<string>

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::endl;
    }

    return 0;
}
  1. 清除状态:如果需要继续使用同一个 std::stringstream 对象,可以使用 clear() 方法清除流的状态。例如:
#include<iostream>
#include <sstream>
#include<string>

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

    return 0;
}
  1. 异常处理:虽然 std::stringstream 不会抛出异常,但你可以设置流的异常掩码,以便在特定条件下抛出异常。例如:
#include<iostream>
#include <sstream>
#include<string>

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.what()<< std::endl;
    }

    return 0;
}

请注意,std::stringstream 不会因为遇到无效输入而抛出异常,除非你显式地设置了异常掩码。在大多数情况下,检查流的状态并根据需要清除错误状态是更好的做法。

0
看了该问题的人还看了