c++ - 将字符串数组转换为 int 数组

标签 c++ linux arrays type-conversion

<分区>

我正在尝试编写一个函数,将字符串数组作为参数,将其转换为 int 数组,然后返回新数组。我认为使用“Atoi”会非常简单,但显然您不能按照我尝试的方式使用它。

到目前为止,这是我的代码。

int GameHandler::convertToInt(string array[])
{
    int tmp=0;
    string arr[20]=array;
    int values[20];
    for(int i=0;i<20;i++)
        values[i]=0;

    for(int i=0;i<20;i++)
    {
        tmp=atoi(arr[i]);
        values[i]=tmp;

    }
    return values;
}

这是我从编译器得到的错误信息:

GameHandler.cpp: In member function ‘int GameHandler::convertToInt(std::string*)’: GameHandler.cpp:60:20: error: conversion from ‘std::string* {aka std::basic_string*}’ to non-scalar type ‘std::string {aka std::basic_string}’ requested GameHandler.cpp:67:24: error: cannot convert ‘std::string {aka std::basic_string}’ to ‘const char*’ for argument ‘1’ to ‘int atoi(const char*)’ GameHandler.cpp:71:12: error: invalid conversion from ‘int*’ to ‘int’ [-fpermissive] GameHandler.cpp:61:9: warning: address of local variable ‘values’ returned [enabled by default]

最佳答案

atoi的签名是

int atoi(const char *str);

因此您需要将 const char* 传递给 atoi,在您的情况下:

tmp=atoi(arr[i].c_str());

关于c++ - 将字符串数组转换为 int 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12821583/

相关文章:

c++ - C++中的结构指针

c++ - blowfish 和 twofish 是逐字节加密的吗?

linux - 限制linux中的物理内存

python - NumPy 数组元素未更新

php - 根据表jquery中的数据填充多维数组

c++ - Qt 项目的通用 Makefile

c++ - OpenCV 轮廓时刻?

c++ - 访问文件和打开文件有什么区别

linux - 在 linux build/temp.linux-x86_64-3.6/_clips.c 上安装 clipspy :523:19: fatal error: clips. h : No such file or directory #include <clips. h>

c++ - 我可以防止对非 POD 类中的数组数据成员中的元素进行零初始化吗?