In deze tutorial zullen we leren hoe we string naar int en vice versa kunnen converteren met behulp van voorbeelden.
C ++ string naar int Conversion
We kunnen op meerdere manieren converteren string
naar int
. De eenvoudigste manier om dit te doen, is door de std::stoi()
functie te gebruiken die is geïntroduceerd in C ++ 11 .
Voorbeeld 1: C ++ string to int met 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; )
Uitvoer
123
Voorbeeld 2: char Array to int Atoi () gebruiken
We kunnen een char
array converteren naar het int
gebruik van de std::atoi()
functie. De atoi()
functie is gedefinieerd in het cstdlib
header-bestand.
#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; )
Uitvoer
num = 456
Om andere manieren te leren om strings naar gehele getallen te converteren, ga je naar Verschillende manieren om C ++ string naar int te converteren
C ++ int naar string Conversion
We kunnen converteren int
naar het string
gebruik van de C ++ 11- std::to_string()
functie. Voor oudere versies van C ++ kunnen we std::stringstream
objecten gebruiken.
Voorbeeld 3: C ++ int to string met to_string ()
#include #include using namespace std; int main() ( int num = 123; std::string str = to_string(num); std::cout << str; return 0; )
Uitvoer
123
Voorbeeld 4: C ++ int naar string Stringstream gebruiken
#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; )
Uitvoer
15
Voor meer informatie over het converteren van een string naar float / double, bezoek C ++ String to float / double.