如何在C++中使用atoi函数处理字符串?

5

这是一个基本问题。我使用的是C++,但不是C++11。现在,我想将一个字符串转换为整数。我的声明如下:

string s;

int i = atoi(s);

但是,出现了无法进行此类转换的错误。我查阅了互联网,发现C++11有stoi()函数,但我想使用atoi本身。我该怎么做?谢谢!


为什么不能使用C++11?(只是好奇) - wingerse
我想这样做,但问题是,我正在一个在线网站上练习问题,它不接受C++11。因此,我只能使用C++98。这就是为什么。 - John Yad
我强烈建议您使用一些好书,比如C++ Primer。大多数编译器都建议使用C++11。这将真正让您的生活更轻松。请参见此链接:https://dev59.com/_3RC5IYBdhLWcg3wK9yV - wingerse
4个回答

15

将其转换为C字符串,然后您就完成了

string s;

int i = atoi(s.c_str());

3
若您认为这是最佳答案,请点击帖子左侧的勾选标记接受它。 - wingerse

0

请使用

int i = atoi( s.c_str() );

0
// 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
     }
 }

0

还有 strtol() 和 strtoul() 函数族,你可能会发现它们在不同的进制等方面很有用


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接