在C++中,std::stringstream
類提供了一系列方法來執行類型轉換。以下是一些常用的類型轉換方法:
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;
}
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;
}
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()
等方法來清除錯誤標志和忽略無效輸入。