C/C++ 中的类型相互转换
发布日期:2021-05-07 22:09:33 浏览次数:21 分类:精选文章

本文共 2753 字,大约阅读时间需要 9 分钟。

类型转换

在编程中经常会遇到,各种基本数据类型的相互转换的需求,比如整型转字符串类型,字符串转整型等等。最常见的类型转换是数字类型(int 、float等等)和字符串之间的转换。本文主要介绍整型和字符串或字符之间的转换。

一、字符串类型转整型

1.1 利用stringstream

stringstream字符串流数据类的头文件是<sstream>,该头文件的数据类主要是对string类型字符串进行操作,包括输入输出操作,其中stringstream既可以进行输入操作也可以进行输出操作。除此之外,也可以定义单独的输出和输入的字符串数据流:ostringstream,输出;istringstream。

#include 
#include
#include
using namespace std; // 注意stringstream在std的命名空间中int main(){ string str = "123"; stringstream ss; int num; // 将string类型的变量str的值数输出到ss中 ss << str; // 将ss中的str字符串输入到整型变量num中 ss >> num; // 可以输出测试一下 cout << "value test: " << num << endl; return 0;}

1.2 利用C++函数stoi()函数

stoi()函数的头文件是<cstring>,该函数的操作是将string类型字符串转换为int类型。

该函数的函数原型如下:

int stoi (const string&  str, size_t* idx = 0, int base = 10);int stoi (const wstring& str, size_t* idx = 0, int base = 10);

从函数stoi()原型的中可得如下代码:

#include 
#include
#include
using namespace std; // 注意stringstream在std的命名空间中int main(){ string str = "123"; int num = stoi(str); // 可以输出测试一下 cout << "value test: " << num << endl; return 0;}

<cstring> 头文件中还提供字符串转浮点型的函数stof()。应该注意的是对于不是数字的字符串函数stoi()函数会抛出异常,因此在使用此类函数时最好要进行异常处理。

#include 
#include
#include
using namespace std; // 注意stringstream在std的命名空间中int main(){ string str = "123"; try{ int num = stoi(str); } // 如果没有转换发生则抛出无效参数异常 catch(std::invalid_argument&){ cout<<"nvalid_argument" << endl; } // 如果转换后的值超过定义的整型范围,则抛出溢出异常 catch(std::out_of_range&){ cout<<"out of range" <

如果是C字符串则可以使用atoi()函数转换:

#include 
int atoi(const char *nptr);

注意由于该函数的字符串输入参数是const char* 的C语言类型字符串,因此如果是string类型的输入因该先转化为C字符串类型

#include 
#include
#include
using namespace std; // 注意stringstream在std的命名空间中int main(){ char* str = "123"; int num = atoi(str); // 可以输出测试一下 cout << "value test: " << num << endl; return 0;}

二、整型转字符串

2.1 利用stringstream

#include 
#include
#include
using namespace std;int main(){ stringstream ss; int num = 123; ss << num; string str; ss >> str; cout << "Value test: " << str << endl; return 0;}

2.2 利用C++ 11 新特性to_string()函数

#include 
#include
using namespace std;int main(){ int num = 123; string str = to_string(num); cout << "Value test: " << str <<< endl; return 0;}

2.3 利用sprintf()

如果整型要转换为C类型的字符串。函数头文件和原型如下:

#include 
int sprintf(char *buffer, const char *format, [argument]...)// 参数说明:// buffer: char类型的指针,指向写入的字符串指针// format: 格式化字符串,即:程序中需要的格式// argument: 可选参数,可以是任意类型的数据,也可以不止一个// 该函数返回的是buffer指向的字符串长度

用法如下:

#include 
#include
using namespace std;int main(){ char* buf; int num = 123; sprintf(buf, "%d",num); cout << "test: " << buf << endl; return 0;}
上一篇:OpenCV的stitching.hpp 和X11的Xlib.h的‘Status’ 冲突解决方法
下一篇:C++中的引用‘&‘和指针的区别,以及指针使用的注意事项

发表评论

最新留言

路过,博主的博客真漂亮。。
[***.116.15.85]2025年04月11日 03时36分22秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章