溫馨提示×

c++的stringstream類怎么使用

小億
87
2023-07-07 14:44:48
欄目: 編程語言

stringstream類是C++標準庫中的一個類,用于處理字符串流。它可以將字符串轉(zhuǎn)換為各種類型的數(shù)據(jù),并將各種類型的數(shù)據(jù)轉(zhuǎn)換為字符串。

使用stringstream類需要包含頭文件。

下面是stringstream類的一些常用方法和示例:

  1. 創(chuàng)建stringstream對象:
#include <sstream>
std::stringstream ss;
  1. 向stringstream對象中寫入數(shù)據(jù):
ss << "Hello";    // 寫入字符串
ss << " " << 123; // 寫入整數(shù)
ss << " " << 3.14; // 寫入浮點數(shù)
  1. 從stringstream對象中讀取數(shù)據(jù):
std::string str;
int num;
double dbl;
ss >> str;   // 讀取字符串
ss >> num;   // 讀取整數(shù)
ss >> dbl;   // 讀取浮點數(shù)
  1. 轉(zhuǎn)換為字符串:
std::string result = ss.str();

完整示例:

#include <iostream>
#include <sstream>
int main() {
std::stringstream ss;
ss << "Hello";
ss << " " << 123;
ss << " " << 3.14;
std::string str;
int num;
double dbl;
ss >> str;
ss >> num;
ss >> dbl;
std::cout << "String: " << str << std::endl;
std::cout << "Integer: " << num << std::endl;
std::cout << "Double: " << dbl << std::endl;
std::string result = ss.str();
std::cout << "Result: " << result << std::endl;
return 0;
}

上述示例輸出:

String: Hello
Integer: 123
Double: 3.14
Result: Hello 123 3.14

希望對你有幫助!

0