0

我有一个字符串数组和一个整数数组。我想将字符串数组的元素转换为整数,然后将它们存储在整数数组中。我写了这段代码:

string yuzy[360];
int yuza[360];

for(int x = 0;x<360;x++)
{
    if(yuzy[x].empty() == false)
    {

         yuza[x]=atoi(yuzy[x]);
         cout<<yuza[x]<<endl;
    }
    else
        continue;
}

这段代码给出了这个错误:error: cannot convert 'std::string {aka std::basic_string}' to 'const char*' for argument '1' to 'int atoi(const char*)'

当我在 atoi 函数中写入字符串(-75dbm)的内容时,它工作正常。但是当我写 (yuzy[x]) 时,我得到了错误。如何使 atoi 与字符串数组一起工作?谢谢。

4

3 回答 3

8

atoi()接受 C 字符串(字符指针)而不是 C++ 字符串对象。利用

atoi(yuzy[x].c_str());

反而。

于 2012-08-03T07:21:16.780 回答
3

作为 的替代方法,如果您支持 C++11 atoi,您可以使用std::stoi和相关函数。

yuza[x] = std::stoi(yuzy[x]);
于 2012-08-03T07:24:05.870 回答
1

atoi接受一个 c 风格的字符串作为参数,所以,你可以使用atoi(yuzy[x].c_str());

于 2012-08-03T07:23:34.053 回答