您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Linux C++开发中,进行数据格式转换通常需要使用标准库中的函数或者第三方库
std::stoi
函数将字符串转换为整数。例如:#include <iostream>
#include <string>
int main() {
std::string str_num = "123";
int num = std::stoi(str_num);
std::cout << "转换后的整数: " << num << std::endl;
return 0;
}
std::to_string
函数将整数转换为字符串。例如:#include <iostream>
#include <string>
int main() {
int num = 123;
std::string str_num = std::to_string(num);
std::cout << "转换后的字符串: " << str_num << std::endl;
return 0;
}
std::stod
函数将字符串转换为浮点数。例如:#include <iostream>
#include <string>
int main() {
std::string str_num = "123.45";
double num = std::stod(str_num);
std::cout << "转换后的浮点数: " << num << std::endl;
return 0;
}
std::to_string
函数将浮点数转换为字符串。例如:#include <iostream>
#include <string>
int main() {
double num = 123.45;
std::string str_num = std::to_string(num);
std::cout << "转换后的字符串: " << str_num << std::endl;
return 0;
}
iconv
库进行字符编码转换。例如,将UTF-8编码的字符串转换为GBK编码:#include <iostream>
#include <string>
#include <iconv.h>
#include <locale.h>
std::string utf8_to_gbk(const std::string& utf8_str) {
iconv_t cd = iconv_open("GBK", "UTF-8");
if (cd == (iconv_t)-1) {
std::cerr << "iconv_open failed" << std::endl;
return utf8_str;
}
size_t in_size = utf8_str.size();
size_t out_size = in_size * 4; // GBK编码下最大为4字节
char* in_buf = const_cast<char*>(utf8_str.data());
char* out_buf = new char[out_size];
char* out_buf_start = out_buf;
if (iconv(cd, &in_buf, &in_size, &out_buf, &out_size) == (size_t)-1) {
std::cerr << "iconv failed" << std::endl;
delete[] out_buf_start;
iconv_close(cd);
return utf8_str;
}
std::string gbk_str(out_buf_start, out_buf - out_buf_start);
delete[] out_buf_start;
iconv_close(cd);
return gbk_str;
}
int main() {
std::string utf8_str = "你好,世界!";
std::string gbk_str = utf8_to_gbk(utf8_str);
std::cout << "转换后的字符串: " << gbk_str << std::endl;
return 0;
}
这些示例展示了如何在Linux C++开发中进行基本的数据格式转换。根据实际需求,你可能需要使用其他库或函数来完成更复杂的转换任务。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。