c++ 数字与字符串的相互转换
1.数字转换为字符串
- 方法一(利用
<sstream>
的stringstream,可以是浮点数)
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
double x;
string str;
stringstream ss;
cin >> x;
ss << x;
ss >> str;
cout << str;
return 0;
}
- 方法二(利用
<sstream>
中的to_string()方法,浮点数会附带小数点后六位,不足补零,不推荐浮点数使用)
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
double x;
string str;
cin >> x;
str = to_string(x);
cout << str;
return 0;
}
2.字符串转换为数字
- 方法一(利用
<sstream>
的stringstream,可以是浮点数)
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
double x;
string str;
stringstream ss;
cin >> str;
ss << str;
ss >> x;
cout << x;
return 0;
}
- 方法二(利用
<string>
中的stoi()函数,其中还有对于其他类型的函数,如stod(),stof()等,根据类型选取)
#include <iostream>
#include <string>
using namespace std;
int main()
{
int x;
string str;
cin >> str;
x = stoi(str);
cout << x;
return 0;
}
本文作者:又一岁荣枯
本文链接:https://www.cnblogs.com/java-six/p/16097560.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步