C++标准库string与常见数据类型的相互转换

    xiaoxiao2024-11-02  77

    从其他博客学到的,自己又拓展了一下

    参考博文:https://blog.csdn.net/na_beginning/article/details/53576123 https://blog.csdn.net/lanzhihui_10086/article/details/39995869

    正题开始:

    一、string转long long , int , double

    预备知识

    atoi()函数 atoi():int atoi(const char *str ); 功能:把字符串转换成整型数。 str:要进行转换的字符串 返回值:每个函数返回 int 值,此值由将输入字符作为数字解析而生成。 如果该输入无法转换为该类型的值,则atoi的返回值为 0。 说明:当第一个字符不能识别为数字时,函数将停止读入输入字符串。

    #include<bits/stdc++.h> using namespace std; int main() { //第一种方式 string s1="1234567890123456789"; long long a=atoll(s1.c_str()); cout<<a<<endl; string s2="123456789"; int b=atoi(s2.c_str()); cout<<b<<endl; string s3="3.1415926"; double c=atof(s3.c_str()); cout<<c<<endl; //第二种方式 istringstream is1("1234567890123456789"); //构造输入字符串流,流的内容初始化为“1234567890123456789”的字符串is1 long long d; is1>>d;//从is1流中读入一个long long整数存入要存的整数中 cout<<d<<endl; istringstream is2("123456789"); int e; is2>>e; cout<<e<<endl; istringstream is3("3.14159");//注意只能到五位,因为double的精度 double f; is3>>f; cout<<f<<endl; return 0; }

    输出结果

    二、long long , int , double转string

    采用sstream中定义的字符串流对象来实现。

    #include<bits/stdc++.h> using namespace std; int main() { ostringstream s1; //构造一个输出字符串流,流内容为空 int a = 123456789; s1 << a; //向输出字符串流中输出int整数a的内容(<<表示流向) cout << s1.str() << endl; //利用字符串流的str函数获取流中的内容 ostringstream s2; long long b = 1234567890123456789; s2 << b; cout << s2.str() << endl; ostringstream s3; double c = 3.14159; s3 << c; cout << s3.str() << endl; return 0; }

    输出结果 还有一种C++11才能用的

    采用标准库中的to_string函数。

    int i = 12; cout << std::to_string(i) << endl;

    就学了这些,以后还有会补充

    如有错误还望大佬指正orz

    最新回复(0)