c++中int与char,string的相互转换

1.ASCLL表

这里我们主要关注的是0-9对应的ASCLL码值为48-57.

2.char转int

在char类型字符相减时,结果会自动转为int型:

char a = '1';
cout << typeid(a - '0').name() << endl;
cout << a - '0' << endl;

输出就为int,1

如果是char类型减去数字,结果也是int类型:

char a = '1';
cout << typeid(a - 0).name() << endl;
cout << a - '0' << endl;

输出为int,47。即直接将'a'转为为对应的ASCLL码做计算。

3.int转char

int a = 1;
char b = a + '0';
cout << typeid(a +'0').name() << endl;
cout << b << endl;

a+'0'为int类型,对应的时a和'0'的ASCLL码相加,赋值给char类型的b就自动转为char类型。

输出为int,1(这里的1为字符)。


4.int转string

上面我们只讨论了0-9的数字转char,那如果是12394这样的数呢?

首先这肯定不是int转char,那int转string怎么做呢?我这里也随便写了一下(记得#include<string>哦):

int a = 12394;
string s;
//这里为了装逼将for循环融到一行里了,乍一看有点厉害,仔细看也就那样
for (int k=a%10; a > 0; a /= 10, k = a % 10) s.push_back(k+'0');
reverse(s.begin(), s.end());
cout << s << endl;

输出为string类型的12394。

在写上面程序第二天我发现了to_string。。。

string s = to_string(a);//将整数a转换为字符型

5.string转int

int stoi (const string&  str, size_t* idx = 0, int base = 10);
//str为字符串,idx为字符串中指向数值后面的下一位元素的指针,base为字符串的进制
// stoi example
#include <iostream>   // std::cout
#include <string>     // std::string, std::stoi

int main ()
{
  std::string str_dec = "2001, A Space Odyssey";
  std::string str_hex = "40c3";
  std::string str_bin = "-10010110001";
  std::string str_auto = "0x7f";

  std::string::size_type sz;   // alias of size_t

  int i_dec = std::stoi (str_dec,&sz);
  int i_hex = std::stoi (str_hex,nullptr,16);
  int i_bin = std::stoi (str_bin,nullptr,2);
  int i_auto = std::stoi (str_auto,nullptr,0);

  std::cout << str_dec << ": " << i_dec << " and [" << str_dec.substr(sz) << "]\n";
  std::cout << str_hex << ": " << i_hex << '\n';
  std::cout << str_bin << ": " << i_bin << '\n';
  std::cout << str_auto << ": " << i_auto << '\n';

  return 0;
}

输出:

发布了57 篇原创文章 · 获赞 260 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_40692109/article/details/104466784