Thursday, January 23, 2025
HomeConversionsConvert String to int in C++

Convert String to int in C++

To convert a string to an integer in C++, you can use the stoi function (available in C++11 and later) or use stringstream. Below are examples for both approaches:

Using stoi (C++11 and later):

#include <iostream>
#include <string>

int main() {
    std::string str = "12345";
    int num = std::stoi(str);  // Convert string to int
    std::cout << "Converted number: " << num << std::endl;
    return 0;
}

Using stringstream:

#include <iostream>
#include <string>
#include <sstream>

int main() {
    std::string str = "12345";
    std::stringstream ss(str);
    int num;
    ss >> num;  // Convert string to int using stringstream
    std::cout << "Converted number: " << num << std::endl;
    return 0;
}

Both methods work well, but stoi is more straightforward and recommended for simplicity.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x