String C ++ para int e vice-versa

Neste tutorial, aprenderemos como converter string em int e vice-versa com a ajuda de exemplos.

C ++ string para conversão int

Podemos converter stringpara intde várias maneiras. A maneira mais fácil de fazer isso é usando a std::stoi()função introduzida no C ++ 11 .

Exemplo 1: string C ++ para int Usando stoi ()

 #include #include int main() ( std::string str = "123"; int num; // using stoi() to store the value of str1 to x num = std::stoi(str); std::cout << num; return 0; )

Resultado

 123

Exemplo 2: char Array to int Usando atoi ()

Podemos converter um chararray para intusar a std::atoi()função. A atoi()função é definida no cstdlibarquivo de cabeçalho.

 #include // cstdlib is needed for atoi() #include using namespace std; int main() ( // declaring and initializing character array char str() = "456"; int num = std::atoi(str); std::cout << "num = " << num; return 0; )

Resultado

 num = 456

Para aprender outras maneiras de converter strings em inteiros, visite Diferentes maneiras de converter string C ++ em int

C ++ int para conversão de string

Podemos converter intpara stringusar a std::to_string()função C ++ 11 . Para versões mais antigas do C ++, podemos usar std::stringstreamobjetos.

Exemplo 3: C ++ int to string Usando to_string ()

 #include #include using namespace std; int main() ( int num = 123; std::string str = to_string(num); std::cout << str; return 0; )

Resultado

 123

Exemplo 4: C ++ int para string usando stringstream

 #include #include #include // for using stringstream using namespace std; int main() ( int num = 15; // creating stringstream object ss std::stringstream ss; // assigning the value of num to ss ss << num; // initializing string variable with the value of ss // and converting it to string format with str() function std::string str = ss.str(); std::cout << str; return 0; )

Resultado

 15

Para saber como converter uma string para float / double, visite C ++ String para float / double.

Artigos interessantes...