C++中int转为char 以及int 转为string和string 转int和字符串的split

1、对于int 转为char

直接上代码:

正确做法:

void toChar(int b) {
    char u;
    char buffer[65];
    _itoa( b, buffer, 10); //正确解法一
      u = buffer[0]; 
      //u = b + 48; //正确解法二
      u = (char)b ;//GCC下错误
      u = static_cast <char> (b);//GCC下错误
}

不要想当然以为(char)b 就可以,在GCC下这是不行的,推荐用_itoa,标准库函数

2、对于int 转string 

直接用函数to_string

3、对于string 类型的变量input转int 

atoi(input.c_str())

4、字符串的split,分两种

一、用空格分隔字符串 str = "I love China"

istringstream in(str);
for(string word; in>>word; i++) {
cout <<"word is " << word << endl;

输出 : 

I

love

China

二、用特殊符号(比如,)分隔,例如string input = "ab,cd,e"

istringstream in(input);
string s;
vector<string> v;
while(getline(in,s,',')) {
v.push_back(s);
}

最后v = {"ab","cd","e"}


原文地址:https://www.cnblogs.com/yanchengwang/p/6013927.html