C ++从字符串数组转换为int数组而不会使程序崩溃

时间:2015-11-24 10:58:56

标签: c++ stringstream

我正在尝试找到将字符串数组转换为int数组的最简单方法,以便我可以在计算中使用它。到目前为止,Stringstream和stoi都破坏了程序或者没有工作。有帮助吗?谢谢!

int counter = 0;
string nums[51];
while (! rel.eof())
{       
    getline(rel, tuple);
    cout<<tuple<<endl;
    //minituple[counter] = tuple.substr(0,4);
    //counter++;
    istringstream iss(tuple);

    do
    {
        string found_num;
        iss >> found_num;

        if (iss.fail())
            break;

        char goaway;
        goaway = found_num.at(0);
        if (goaway == '\n')
            counter--;
        else if (goaway == ' ')
            counter--;
        {
            nums[counter] = found_num;
            cout << "Substring: " << found_num << endl;
        }
        counter++;
    } while (iss);      
}

int int_nums[51];
for (int i = 0; i <= 51; i++)
{
    if (!nums[i].empty())
    {
        stoi(nums[i]);
    }
}

1 个答案:

答案 0 :(得分:0)

一旦你加载了你的字符串数组,你就可以这样做:

std::transform(std::begin(nums), std::end(nums), std::begin(int_nums), 
               [](auto const &str) { return std::stoi(str); });

LIVE DEMO

相关问题