现在的位置: 首页 > 综合 > 正文

C++中int型与string型互相转换

2014年11月04日 ⁄ 综合 ⁄ 共 412字 ⁄ 字号 评论关闭

本以为这么多年C#经验,学个C++没多难,现在发现错了。C++真TM难。
今天遇到int转string绊了半天,方法很多,不知道为什么搞那么复杂,
我只挑最简单易懂的,管他效率不效率的。
int转string
int n = 0;
std::stringstream ss;
std::string str;
ss<<n;
ss>>str;
string转int
std::string str = "123";
int n = atoi(str.c_str());

#include "stdafx.h"

#include <string>
#include <sstream>

using namespace std;
void main()
{
    // int 转 string
    stringstream ss;
    int n = 123;
    string str;
    ss<<n;
    ss>>str;
    // string 转 int
    str = "456";
    n = atoi(str.c_str());
}

抱歉!评论已关闭.