C++中 int 与 string 的转换

清疚 2022-03-27 07:16 302阅读 0赞

1. int 转为 string

1.1 to_string

  1. c++11标准增加了全局函数to\_string
  2. int main()
  3. {
  4. string str = "April's age is: " + to_string(18);
  5. cout << str << endl;
  6. return 0;
  7. }
  8. 输出结果:
  9. April's age is: 18

1.2 ostringstream

采用字符串流对象来实现。

  1. int main()
  2. {
  3. int age = 18;
  4. ostringstream os; //构造字符串流
  5. os << age; //向字符串流中写入内容
  6. cout << os.str() << endl; //输出字符串流中的内容
  7. return 0;
  8. }

2.string 转为 int

2.1 stoi

  1. int main()
  2. {
  3. string str_dec = "18";
  4. string str_hex = "40c3";
  5. string str_bin = "10010110001";
  6. string str_auto = "0x7f";
  7. cout << str_dec << ": " << stoi(str_dec) << endl;
  8. cout << str_hex << ": " << stoi(str_hex, nullptr, 16) << endl;
  9. cout << str_bin << ": " << stoi(str_bin, nullptr, 2) << endl;
  10. cout << str_auto << ": " << stoi(str_auto, nullptr, 0) << endl;
  11. return 0;
  12. }

输出结果:

  1. 18: 18
  2. 40c3: 16579
  3. 10010110001: 1201
  4. 0x7f: 127

2.2 istringstream

  1. int main()
  2. {
  3. istringstream is("18"); //构造输入字符串流
  4. int age ;
  5. is >> age;
  6. cout << age << endl;
  7. return 0;
  8. }

输出结果

  1. 18

发表评论

表情:
评论列表 (有 0 条评论,302人围观)

还没有评论,来说两句吧...

相关阅读