C ++ Sträng till int och vice versa

I den här handledningen lär vi oss hur man konverterar sträng till int och vice versa med hjälp av exempel.

C ++ -sträng till int-konvertering

Vi kan konvertera stringtill intpå flera sätt. Det enklaste sättet att göra detta är att använda std::stoi()funktionen som introducerades i C ++ 11 .

Exempel 1: C ++ - sträng till int Använda 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; )

Produktion

 123

Exempel 2: char Array to int Använda atoi ()

Vi kan konvertera en charmatris till att intanvända std::atoi()funktionen. Den atoi()funktionen är definierad i cstdlibheader-filen.

 #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; )

Produktion

 num = 456

Om du vill lära dig andra sätt att konvertera strängar till heltal besöker du olika sätt att konvertera C ++ - sträng till int

C ++ int till strängkonvertering

Vi kan konvertera inttill att stringanvända C ++ 11- std::to_string()funktionen. För äldre versioner av C ++ kan vi använda std::stringstreamobjekt.

Exempel 3: C ++ int till sträng med to_string ()

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

Produktion

 123

Exempel 4: C ++ int till sträng Använd strängström

 #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; )

Produktion

 15

För att veta om hur du konverterar en sträng till float / double, besök C ++ String to float / double.

Intressanta artiklar...