溫馨提示×

stringstream怎樣進行類型轉換

小樊
119
2024-10-16 14:44:15
欄目: 編程語言

在C++中,std::stringstream類提供了一系列方法來執行類型轉換。以下是一些常用的類型轉換方法:

  1. 整數與字符串之間的轉換
  • 使用str()方法將整數轉換為字符串。
  • 使用operator<<將整數插入到stringstream對象中,然后使用str()獲取字符串。
  • 使用ss >>stringstream對象中提取整數。

示例:

#include <iostream>
#include <sstream>
#include <string>

int main() {
    int num = 42;
    std::stringstream ss;

    // 將整數轉換為字符串
    ss << num;
    std::string str = ss.str();
    std::cout << "String: " << str << std::endl;

    // 從字符串中解析整數
    ss.clear(); // 清除錯誤標志
    ss << "123";
    int parsedNum;
    ss >> parsedNum;
    std::cout << "Parsed int: " << parsedNum << std::endl;

    return 0;
}
  1. 浮點數與字符串之間的轉換
  • 使用str()方法將浮點數轉換為字符串。
  • 使用operator<<將浮點數插入到stringstream對象中,然后使用str()獲取字符串。
  • 使用ss >>stringstream對象中提取浮點數。

示例:

#include <iostream>
#include <sstream>
#include <string>

int main() {
    float num = 3.14f;
    std::stringstream ss;

    // 將浮點數轉換為字符串
    ss << num;
    std::string str = ss.str();
    std::cout << "String: " << str << std::endl;

    // 從字符串中解析浮點數
    ss.clear(); // 清除錯誤標志
    ss << "2.718";
    float parsedNum;
    ss >> parsedNum;
    std::cout << "Parsed float: " << parsedNum << std::endl;

    return 0;
}
  1. 字符串與其他類型之間的轉換
  • 使用operator>>stringstream對象中提取特定類型的值。
  • 使用<<操作符將特定類型的值插入到stringstream對象中。

示例:

#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::stringstream ss;
    std::string str;
    int num;
    float fnum;

    // 插入多個值并提取
    ss << "Hello" << " " << 123 << " " << 3.14f;
    getline(ss, str, ' '); // 使用空格作為分隔符
    ss >> num;
    ss >> fnum;

    std::cout << "String: " << str << std::endl;
    std::cout << "Int: " << num << std::endl;
    std::cout << "Float: " << fnum << std::endl;

    return 0;
}

注意:在進行類型轉換時,請確保stringstream對象中的數據格式與要轉換的類型匹配,否則可能會導致錯誤或不可預期的結果。如果需要,可以使用ss.clear()ss.ignore()等方法來清除錯誤標志和忽略無效輸入。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女