Avatar ·

How to convert std::string to int in C++?

Hello everyone! I'm a beginner in C++ and writing a simple program that reads a number from a file and performs arithmetic operations with it. I have a std::string containing a numeric value, for example, "123". I need to convert this string to int so I can add it to another variable. The problem is that I can't just write int number = myString; — the compiler gives an error. I tried using stoi(), but I'm not sure if this is the correct way, especially if the string may contain extra characters (e.g., spaces or letters). I've also heard about atoi(), but they say it's outdated and dangerous. Please advise how to correctly and safely convert std::string to int in modern C++ (preferably C++11 and newer)? I need an example with error handling so the program doesn't crash.