I denne vejledning lærer vi, hvordan man konverterer streng til int og omvendt ved hjælp af eksempler.
C ++ -streng til int-konvertering
Vi kan konvertere string
til int
på flere måder. Den nemmeste måde at gøre dette på er ved hjælp af std::stoi()
funktionen introduceret i C ++ 11 .
Eksempel 1: C ++ streng til int Brug af 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
Eksempel 2: char Array to int Brug af atoi ()
Vi kan konvertere en char
matrix til at int
bruge std::atoi()
funktionen. Den atoi()
funktion er defineret i cstdlib
header-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
tal = 456
Hvis du vil lære andre måder at konvertere strenge til heltal på, skal du besøge forskellige måder for at konvertere C ++ - streng til int
C ++ int til strengkonvertering
Vi kan konvertere int
til string
ved hjælp af C ++ 11- std::to_string()
funktionen. I ældre versioner af C ++ kan vi bruge std::stringstream
objekter.
Eksempel 3: C ++ int til streng ved hjælp af 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
Eksempel 4: C ++ int til streng Brug af 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; )
Produktion
15
Hvis du vil vide om konvertering af en streng til float / double, skal du besøge C ++ String to float / double.