CodeBlanks Logo Icon CodeBlanks

Type conversion

Learn type conversion with stringstream.

Converting a string to a number

The safe way to convert a string to a number is to use istringstream. The >> operator converts the number in the string to the desired type.

Example: std::istringstream iss("42"); int n; iss >> n;. Here the string "42" becomes an int and is stored in n. If the string has non-numeric characters >> fails; so checking the stream state after conversion is a good habit. This method is an alternative to functions like std::stoi and offers more control.

Converting a number to a string

To convert a number to a string you use ostringstream. Write the number to the stream with << and get the string with .str().

Example: std::ostringstream oss; oss << 42; std::string s = oss.str();. Here the number 42 becomes the string "42". This is the safe way to embed a number in a string. The std::to_string(42) function does the same but ostringstream offers formatting options. If you want to combine two numbers in one string you can write oss << a << " " << b; in a single stream.

Practice Convert string to number, add 8, write back

The starting code has a text string containing "42". Convert this string to an int with std::istringstream. Add 8. The result will be 50. Convert the number back to a string with std::ostringstream and print it with std::cout.

Starter code

main.cpp
#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::string text = "42";
    // Convert to number, add 8, print the result

    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::string text = "42";
    std::istringstream iss(text);
    int num;
    iss >> num;
    num += 8;
    std::ostringstream oss;
    oss << num;
    std::cout << oss.str();
    return 0;
}

Expected output

50

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Convert a string to a number

Question
std::istringstream iss("____"); int n; iss >> n;
Answer
std::istringstream iss("42"); int n; iss >> n;

Explanation: The string "42" becomes a number.

2 Match each conversion direction

Term Meaning
istringstream >> n String to number
ostringstream << n Number to string
.str() Getting the string
>> Extracting from stream

3 Which is used to convert an int to a string?

main.cpp
int n = 42;
  • std::ostringstream Correct answer
  • std::ifstream
  • std::vector
  • std::cout

Explanation: ostringstream converts a number to a string.

All lessons in Intermediate