[英]How do I use atoi function with strings in C++
这是一个基本问题。 我使用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() );
还有strtol()和strtoul()函数系列,你可能会发现它们对不同的基数等有用
// atoi_string (cX) 2014 adolfo.dimare@gmail.com
// http://stackoverflow.com/questions/27640333/
#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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.