C++ 字符串转换
外观
C++字符串转换[编辑 | 编辑源代码]
介绍[编辑 | 编辑源代码]
在C++编程中,字符串转换是将一种数据类型转换为字符串(std::string)或反之的过程。字符串转换在数据处理、用户输入解析、文件操作等场景中极为常见。C++提供了多种方法来实现字符串与其他数据类型(如整数、浮点数)之间的转换,包括标准库函数、C风格函数和现代C++方法。
基本转换方法[编辑 | 编辑源代码]
数值到字符串[编辑 | 编辑源代码]
C++11引入了std::to_string
函数,可以方便地将数值类型转换为字符串。
#include <iostream>
#include <string>
int main() {
int num = 42;
double pi = 3.14159;
std::string str_num = std::to_string(num);
std::string str_pi = std::to_string(pi);
std::cout << "整数转换为字符串: " << str_num << std::endl;
std::cout << "浮点数转换为字符串: " << str_pi << std::endl;
return 0;
}
输出:
整数转换为字符串: 42 浮点数转换为字符串: 3.141590
字符串到数值[编辑 | 编辑源代码]
使用std::stoi
, std::stod
等函数可以将字符串转换为数值类型。
#include <iostream>
#include <string>
int main() {
std::string str_num = "123";
std::string str_pi = "3.14159";
int num = std::stoi(str_num);
double pi = std::stod(str_pi);
std::cout << "字符串转换为整数: " << num << std::endl;
std::cout << "字符串转换为浮点数: " << pi << std::endl;
return 0;
}
输出:
字符串转换为整数: 123 字符串转换为浮点数: 3.14159
高级转换方法[编辑 | 编辑源代码]
使用字符串流[编辑 | 编辑源代码]
C++的<sstream>
库提供了更灵活的字符串转换方式。
#include <iostream>
#include <sstream>
#include <string>
int main() {
// 数值到字符串
std::ostringstream oss;
oss << 42 << " " << 3.14159;
std::string combined = oss.str();
std::cout << "使用ostringstream: " << combined << std::endl;
// 字符串到数值
std::istringstream iss("42 3.14159");
int num;
double pi;
iss >> num >> pi;
std::cout << "使用istringstream: " << num << " " << pi << std::endl;
return 0;
}
输出:
使用ostringstream: 42 3.14159 使用istringstream: 42 3.14159
格式化转换[编辑 | 编辑源代码]
可以使用<iomanip>库进行格式化转换。
#include <iostream>
#include <iomanip>
#include <sstream>
int main() {
double pi = 3.141592653589793;
std::ostringstream oss;
oss << std::fixed << std::setprecision(2) << pi;
std::cout << "格式化后的pi: " << oss.str() << std::endl;
return 0;
}
输出:
格式化后的pi: 3.14
实际应用案例[编辑 | 编辑源代码]
案例1:配置文件解析[编辑 | 编辑源代码]
在读取配置文件时,经常需要将字符串转换为数值。
#include <iostream>
#include <fstream>
#include <string>
#include <map>
std::map<std::string, std::string> parseConfig(const std::string& filename) {
std::map<std::string, std::string> config;
std::ifstream file(filename);
std::string line;
while (std::getline(file, line)) {
size_t delimiter = line.find('=');
if (delimiter != std::string::npos) {
std::string key = line.substr(0, delimiter);
std::string value = line.substr(delimiter + 1);
config[key] = value;
}
}
return config;
}
int main() {
auto config = parseConfig("settings.cfg");
int port = std::stoi(config["PORT"]);
double timeout = std::stod(config["TIMEOUT"]);
std::cout << "端口: " << port << ", 超时: " << timeout << std::endl;
return 0;
}
假设settings.cfg内容:
PORT=8080 TIMEOUT=5.5
输出:
端口: 8080, 超时: 5.5
案例2:数据序列化[编辑 | 编辑源代码]
将数据结构转换为字符串以便存储或传输。
#include <iostream>
#include <sstream>
#include <vector>
std::string serializeVector(const std::vector<int>& vec) {
std::ostringstream oss;
for (size_t i = 0; i < vec.size(); ++i) {
if (i != 0) oss << ",";
oss << vec[i];
}
return oss.str();
}
std::vector<int> deserializeVector(const std::string& str) {
std::vector<int> vec;
std::istringstream iss(str);
std::string token;
while (std::getline(iss, token, ',')) {
vec.push_back(std::stoi(token));
}
return vec;
}
int main() {
std::vector<int> data = {1, 2, 3, 4, 5};
std::string serialized = serializeVector(data);
std::cout << "序列化: " << serialized << std::endl;
auto deserialized = deserializeVector(serialized);
std::cout << "反序列化: ";
for (int num : deserialized) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
输出:
序列化: 1,2,3,4,5 反序列化: 1 2 3 4 5
性能考虑[编辑 | 编辑源代码]
不同的转换方法有不同的性能特点:
std::to_string
和std::sto*
系列函数通常是最快的简单转换方法- 字符串流(
stringstream
)更灵活但性能稍差 - 对于大量数据转换,可以考虑使用C风格的
snprintf
或专门的库
错误处理[编辑 | 编辑源代码]
字符串转换可能失败,应该总是检查错误:
#include <iostream>
#include <string>
#include <stdexcept>
int safeStoi(const std::string& str) {
try {
return std::stoi(str);
} catch (const std::invalid_argument& e) {
std::cerr << "无效参数: " << str << std::endl;
return 0;
} catch (const std::out_of_range& e) {
std::cerr << "超出范围: " << str << std::endl;
return 0;
}
}
int main() {
std::cout << safeStoi("123") << std::endl;
std::cout << safeStoi("abc") << std::endl;
std::cout << safeStoi("99999999999999999999") << std::endl;
return 0;
}
输出:
123 无效参数: abc 0 超出范围: 99999999999999999999 0
总结[编辑 | 编辑源代码]
C++提供了多种字符串转换方法,从简单的std::to_string
到灵活的字符串流。选择哪种方法取决于具体需求:
- 简单转换:使用
std::to_string
和std::sto*
- 复杂格式化:使用字符串流和<iomanip>
- 高性能场景:考虑C风格函数或专门库
在实际应用中,应该始终考虑错误处理,特别是当处理用户输入或外部数据时。