The short answer is no
int() does not read digits out of a string. In C++, int is a type, and int(value) converts a numeric value to an int. A std::string has no conversion to int, so int(text) does not compile.
What int() does with numbers
int() works on numeric values. When it converts a floating-point value, it drops the fraction:
#include <iostream>
int main() {
double price = 3.99;
std::cout << int(price) << '\n'; // 3
}
The value is truncated toward zero, so int(-3.99) gives -3.
What int() does with characters
A char is a small integer, so int() returns its character code, not the digit it shows. In the usual ASCII encoding, the character '7' has the code 55:
std::cout << int('7') << '\n'; // 55
std::cout << '7' - '0' << '\n'; // 7
Subtracting '0' gives the digit’s value, because the digit characters are guaranteed to be in order.
Why int() fails on a std::string
#include <string>
int main() {
std::string text = "42";
int value = int(text); // does not compile
}
The compiler reports that there is no conversion from std::string to int. The exact wording depends on the compiler.
Use std::stoi to read the number
std::stoi(), declared in <string>, parses a std::string and returns an int:
#include <iostream>
#include <string>
int main() {
std::string text = "42";
int value = std::stoi(text);
std::cout << value + 1 << '\n'; // 43
}
It skips leading whitespace, accepts an optional sign, and reads digits until it reaches a character that is not a digit. Trailing text is ignored, so std::stoi("42abc") returns 42. If there are no digits at all, it throws std::invalid_argument. If the number does not fit in an int, it throws std::out_of_range.
Other options
std::atoi() comes from C and takes a const char*, so pass text.c_str():
#include <cstdlib>
#include <string>
std::string text = "42";
int value = std::atoi(text.c_str()); // 42
It returns 0 when the text has no digits, so bad input looks like a real zero. Its behavior is undefined when the number does not fit in an int. If you need to detect errors, prefer std::stoi(). The C background is in what does the atoi() function do in C.
A string stream reads values with >>, and the if checks whether the read worked:
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::string text = "42";
std::istringstream in(text);
int value = 0;
if (in >> value) {
std::cout << value << '\n'; // 42
}
}
Single characters
A single character needs the same care as the int('7') example above. For one digit, subtract '0'. The question of single characters has its own answer in can I convert a char to an int.
Summary
int(text)does not compile whentextis astd::string.std::stoi()is the usual choice, and it throws on bad input.std::atoi()returns 0 on bad input, so it cannot tell you when parsing failed.- A string stream works well when you read several values one after another.
For the opposite direction, see how to convert an int to a string in C++.