1. 程式人生 > >c++ to_string、stoi()、atoi()使用

c++ to_string、stoi()、atoi()使用

1、to_string

int a = 4;
double b = 3.14;
string str1, str2;
str1 = to_string(a);
str2 = to_string(b);
cout << str1 << endl;
cout << str2 << endl;

2、stoi和atoi

          包含在#include<string>,不是c++11的可以在#include<cstring>。作用是將字串轉化為int型。區別是stoi的形參是const string*,而atoi的形參是const char*。c_str()的作用是將const string*轉化為const char*。

string s1("1234567");
char* s2 = "1234567";
int a = stoi(s1);
int b = atoi(s2);
int c = atoi(s1.c_str());
cout << a << endl;
cout << b << endl;
cout << c << endl;