数字与字符串相互转化的方法

1.将数字转化为字符串

方法1:

#include<iostream>
using namespace std;
int main() {
    int n = 123;
    cout << to_string(n) << endl; 
    return 0;
}

方法2:

#include <iostream>
#include <sstream> using namespace std; int main() { int n = 123; string s; stringstream stream; stream << n; stream >> s; cout << s << endl; return 0; }

2.将字符串转化为数字

方法1:

#include <iostream>
#include <sstream>//头文件 
using namespace std;
int main() {
    int n;
    string s;
    getline(cin, s);
    stringstream stream;
    stream << s;//将string类型存放在输入流中 
    stream >> n;//将从string类型的值赋给int类型的n 
    cout << n;
    return 0;
} 

方法2:

将字符串类型转化为整型 (c++11)

#include <iostream>
#include <cstring> //函数的头文件 
using namespace std;
int main() {
string s = "123";
int n = stoi(s);
cout << n;
return 0;
}

 

原文链接: https://www.cnblogs.com/captand/p/13299134.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    数字与字符串相互转化的方法

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/365888

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 下午4:24
下一篇 2023年3月2日 下午4:25

相关推荐