Converting String to Number and Vice-Versa in C++
In general or more specifically in competitive programming there are many instances where we need to convert a number to a string or string to a number. But lack of knowledge of certain essential tools binds us to do so. Some methods to achieve this task are mentioned in this article.
Converting String to Number
Method 1: Using stringstream class or sscanf(): stringstream is a convenient way to manipulate strings. sscanf() is a C style function similar to scanf(). It reads input from a string rather than standard input.
Method 2: String conversion using stoi() or atoi().
- stoi() : The stoi() function takes a string as an argument and returns its value.
- atoi() : The atoi() function takes a character array or string literal as an argument and returns its value.
Both these methods have been discussed in detail in this article.
Method 3: Using boost lexical cast: Boost library offers an inbuild function “lexical_cast(“string”)”, which directly converts a string to a number. It returns an exception “bad_lexical_cast” in case of invalid input.
The float value after casting is : 6.5 The int value after casting is : 5
Converting Number to String
Method 1: Using string streams: In this method, a string stream declares a stream object which first inserts a number, as a stream into an object and then uses “str()” to follow the internal conversion of number to string.
The newly formed string from number is : 2016
Method 2: Using to_string() : This function accepts a number(can be any data type) and returns the number in the desired string.
The integer in string is : 20 The float in string is : 30.500000
Method 3: Using boost lexical cast: Similar to string conversion, the ” lexical_cast() ” function remains the same, but this time argument list modifies to “lexical_cast(numeric_var).
The float value in string is : 10.5 The int value in string is : 17
This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.