Introduction: The Eternal Question of "std::string to int"
\n\nHello, fellow programmer! If you've ever written a config parser in C++, processed user input, or extracted numbers from a CSV file, you've undoubtedly faced the task: "How do I convert a regular string (std::string) into an integer (int)?" It seems simple enough, right? However, a quick look at Stack Overflow reveals thousands of votes and dozens of answer options. Why? Because behind this simple question lies a whole world of trade-offs between convenience, safety, and performance.
In this article, we won't just give you a dry answer. We'll stage a real battle between the main conversion methods: std::stoi, std::from_chars (C++17), std::stringstream, the good old atoi, and we'll even write our own custom solution. You'll learn which method to choose for a high-load server and which one for a quick prototype. Let's go!
Method 1: The Classic — std::stoi (C++11)
\n\nStarting with C++11, the standard library introduced the elegant function std::stoi. It's simple, readable, and throws exceptions on errors. This is the choice of 90% of developers for everyday tasks.
#include <iostream>\n#include <string>\n\nint main() {\n std::string number_str = "12345";\n try {\n int value = std::stoi(number_str);\n std::cout << "Number: " << value << std::endl;\n } catch (const std::invalid_argument& e) {\n std::cerr << "Error: string does not contain a number!" << std::endl;\n } catch (const std::out_of_range& e) {\n std::cerr << "Error: number is out of int range!" << std::endl;\n }\n return 0;\n}\n\nPros and Cons of std::stoi
\n- \n
- Pros: Simplicity, locale support (recognizes commas as separators), automatic error handling via exceptions. \n
- Cons: Exceptions are expensive. If you are parsing millions of numbers in a loop,
try-catchcan significantly slow down your code. \n
Method 2: Faster Than the Wind — std::from_chars (C++17)
\n\nIf you are writing a high-load application where every nanosecond counts, then std::from_chars is your hero. This function does not allocate memory, does not throw exceptions, and is locale-independent. It simply converts characters to a number and returns a pointer to where it stopped.
#include <iostream>\n#include <charconv>\n#include <string>\n#include <system_error>\n\nint main() {\n std::string number_str = "98765";\n int value = 0;\n auto [ptr, ec] = std::from_chars(number_str.data(), \n number_str.data() + number_str.size(), \n value);\n if (ec == std::errc()) {\n std::cout << "Number: " << value << std::endl;\n } else {\n std::cerr << "Conversion error!" << std::endl;\n }\n return 0;\n}\n\nWhy from_chars is the King of Performance?
\n- \n
- Zero-overhead: No exceptions, no hidden allocations. \n
- Localization disabled: No time wasted checking decimal separators. \n
- Returns the remainder of the string: Ideal for parsing columns in CSV. \n
According to benchmarks, from_chars can be 2-10 times faster than stoi, especially on short strings.
Method 3: The Heavy Artillery — std::stringstream
\n\nMany beginner programmers use std::stringstream for conversion. It's a powerful tool, but for the "string to number" task, it's as overkill as using a tank to drive to the store for bread.
#include <sstream>\n#include <string>\n#