溫馨提示×

stringstream在異常情況下的處理

小樊
127
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女