回覆列表
  • 1 # 使用者834195712159

    1 概述

    <sstream> 定義了三個類:istringstream、ostringstream 和 stringstream,分別用來進行流的輸入、輸出和輸入輸出操作。本文以 stringstream 為主,介紹流的輸入和輸出操作。

    <sstream> 主要用來進行資料型別轉換,由於 <sstream> 使用 string 物件來代替字元陣列(snprintf方式),就避免緩衝區溢位的危險;而且,因為傳入引數和目標物件的型別會被自動推匯出來,所以不存在錯誤的格式化符的問題。簡單說,相比c庫的資料型別轉換而言,<sstream> 更加安全、自動和直接。

    2 程式碼示例

    2.1 資料型別轉換

    這裡展示一個程式碼示例,該示例介紹了將 int 型別轉換為 string 型別的過程。示例程式碼(stringstream_test1.cpp)如下:

    #include <string>

    #include <sstream>

    #include <iostream>

    #include <stdio.h>

    using namespace std;

    int main()

    {

    stringstream sstream;

    string strResult;

    int nValue = 1000;

    // 將int型別的值放入輸入流中

    sstream << nValue;

    // 從sstream中抽取前面插入的int型別的值,賦給string型別

    sstream >> strResult;

    cout << "[cout]strResult is: " << strResult << endl;

    printf("[printf]strResult is: %s\n", strResult.c_str());

    return 0;

    }

  • 中秋節和大豐收的關聯?
  • c#裡如何定義一個可變長度的二維陣列?