How can I convert a std::string to int?
In C++11 there are some nice new convert functions from std::string
to a number type.
So instead of
atoi( str.c_str() )
you can use
std::stoi( str )
where str
is your number as std::string
.
There are version for all flavours of numbers:long stol(string)
, float stof(string)
, double stod(string)
,...
see http://en.cppreference.com/w/cpp/string/basic_string/stol
C++ convert string to int
You can check the number of characters processed.
string str2 = "31337 test";
std::size_t num;
int myint2 = stoi(str2, &num); // 31337
// ^^^^
// num (the number of characters processed) would be 5
if (num != str2.length()) {
...
}
Convert std::string to integer
With C++11:
int value = std::stoi(record[i]);
Converting a std::string to int in C++03
You're almost there. After you do the conversion you need to check if there is any data left in the stream. If there is then you know you had invalid input. So if
the_stream.eof()
is true
then you consumed on the input and you have a valid result. If not then you have invalid input.
How to convert a part of string into integer?
Another way: You could replace non-digits with spaces so as to use stringstring
extraction of the remaining integers directly:
std::string x = "15a16a17";
for (char &c : x)
{
if (!isdigit(c))
c = ' ';
}
int v;
std::stringstream ss(x);
while (ss >> v)
std::cout << v << "\n";
Output:
15
16
17
How to properly convert std::string to an integer vector
However C++ code outputs [116, 101, 115, 116, -50, -108].
In C++, the char
type is separate from both signed char
and unsigned char
, and it is unspecified whether or not it should be signed.
You thus explicitly want an unsigned char*
, but the .c_str
method gives you char *
, so you need to cast. You will need reinterpret_cast
or a C-style cast; static_cast
will not work.
Related Topics
C++ Reading CSV File and Assigning Values to Array
Correct Way of Passing Pointer to Another Thread
C++: How to Iterate Over Each Char in a String
How Come a Non-Const Reference Cannot Bind to a Temporary Object
Undefined Behavior and Sequence Points
What Is the Strict Aliasing Rule
Why Does Std::Getline() Skip Input After a Formatted Extraction
What Are Copy Elision and Return Value Optimization
Visual Studio Code: Take Input from User
How to Print Current Time (With Milliseconds) Using C++/C++11
Most Efficient Way to Compare a Variable to Multiple Values
How to Fully Disable Resizing a Window Including the Resize Icon When the Mouse Hovers the Border
Countdown Until Matching Digits