Convert String to Integer

Convert String to Integer in C++

C++Beginner
C++
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main() {
    string str = "12345";
    
    // Method 1: Using stoi()
    int num1 = stoi(str);
    
    // Method 2: Using stringstream
    stringstream ss(str);
    int num2;
    ss >> num2;
    
    cout << "String: " << str << endl;
    cout << "Integer (method 1): " << num1 << endl;
    cout << "Integer (method 2): " << num2 << endl;
    
    return 0;
}

Output

String: 12345
Integer (method 1): 12345
Integer (method 2): 12345

Convert String to Integer in C++

This program teaches you how to convert a string containing numeric characters into an integer in C++. This is one of the most common operations in programming, especially when reading user input, parsing files, or processing data from external sources. Understanding different conversion methods helps you choose the best approach for your specific needs.

What This Program Does

The program converts a string like "12345" into an integer value 12345. This conversion is necessary because:

  • User input from cin is often read as strings
  • File data is typically read as strings
  • Network data comes as strings
  • You need integers for mathematical operations

Example:

  • Input string: "12345"
  • Output integer: 12345

Methods for Conversion

Method 1: Using stoi() (String to Integer)

cpp
int num1 = stoi(str);
  • Most modern and recommended method in C++
  • Part of the <string> header (C++11 and later)
  • Automatically handles the conversion
  • Throws exceptions for invalid input
  • Handles leading/trailing whitespace automatically

Method 2: Using stringstream

cpp
stringstream ss(str);
int num2;
ss >> num2;
  • Very flexible - can convert multiple values
  • Similar syntax to cin, making it familiar
  • Can handle multiple types in one stream

Error Handling

Different methods handle errors differently:

  • stoi(): Throws std::invalid_argument or std::out_of_range exceptions

  • stringstream: Sets failbit on error

  • Best Practice: Use stoi() with try-catch for robust error handling

Summary

  • Converting strings to integers is essential for processing user input and data.
  • stoi() is the recommended modern C++ method - simple and safe.
  • stringstream is flexible and great for multiple conversions.
  • Always handle errors appropriately, especially with user input.

This program is crucial for beginners learning how to work with different data types and process user input in C++ programs.