这是一个基本问题。我使用的是C++,但不是C++11。现在,我想将一个字符串转换为整数。我的声明如下:
string s;
int i = atoi(s);
但是,出现了无法进行此类转换的错误。我查阅了互联网,发现C++11有stoi()函数,但我想使用atoi本身。我该怎么做?谢谢!
这是一个基本问题。我使用的是C++,但不是C++11。现在,我想将一个字符串转换为整数。我的声明如下:
string s;
int i = atoi(s);
但是,出现了无法进行此类转换的错误。我查阅了互联网,发现C++11有stoi()函数,但我想使用atoi本身。我该怎么做?谢谢!
将其转换为C字符串,然后您就完成了
string s;
int i = atoi(s.c_str());
请使用
int i = atoi( s.c_str() );
// atoi_string (cX) 2014 adolfo.dimare@gmail.com
// https://dev59.com/GIbca4cB1Zd3GeqPUlz6
#include <string>
/// Convert 'str' to its integer value.
/// - Skips leading white space.
int atoi( const std::string& str ) {
std::string::const_iterator it;
it = str.begin();
while ( isspace(*it)) { ++it; } // skip white space
bool isPositive = true;
if ( *it=='-' ) {
isPositive = false;
++it;
}
int val = 0;
while ( isdigit(*it) ) {
val = val * 10 + (*it)-'0';
}
return ( isPositive ? val : -val );
}
#include <cassert> // assert()
#include <climits> // INT_MIN && INT_MAX
#include <cstdlib> // itoa()
int main() {
char mem[ 1+sizeof(int) ];
std::string str;
for ( int i=INT_MIN; true; ++i ) {
itoa( i, mem, 10 );
str = mem;
assert( i==atoi(str) ); // never stops
}
}
还有 strtol() 和 strtoul() 函数族,你可能会发现它们在不同的进制等方面很有用