【问题标题】:How to convert string array to integer array in C++?如何在 C++ 中将字符串数组转换为整数数组?
【发布时间】:2021-04-24 06:55:06
【问题描述】:

我有一串非均匀空格分隔的整数,我想对元素做一些算术运算,所以我决定先将字符串转换为整数数组。以下是我的做法:

    string s;                //let s="1   2 30 54  899 2 7   3 1";
    cin>>s;
    int n=s.length();
    vector<int>arr(n);

    for(int i=0;i<n;i++)
    {
        if(s[i]==' ')continue;
        else{
            arr.push_back(s[i]-'0');
        }
    }
    for(int i=0;i<n;i++)
    {
        cout<<arr[i]<<endl; // arr should be{1,2,30,54,899,2,7,3,1};
    }

这种方法有什么问题?

【问题讨论】:

  • 请不要添加与问题无关的语言标签

标签: c++ arrays string c++17


【解决方案1】:

这种方法有什么问题?

  • operator&gt;&gt; 只提取直到std::cin 中第一个遇到满足std::isspace() 的字符,所以s 不可能在您的程序中初始化为包含空格的字符串。
  • 您假设字符串n 的长度应该是数组的长度。字符数不等于空格分隔值的数量。
  • 您将arr 初始化为长度n,然后使用push_back()。您应该默认初始化向量,使其开始为空。
  • 您将每个字符与字符串分开读取,并将 push_back() 每个数字作为单独的元素读取。

您可以使用std::getline() 来初始化来自std::cinstd::istringstream 的字符串,以简化格式化整数的提取:

#include <string>
#include <iostream>
#include <sstream>
#include <vector>

int main()
{
    std::string s;
    std::getline(std::cin, s);
    std::istringstream iss(s);
    std::vector<int> arr;

    for (int i; iss >> i;) {
        arr.push_back(i);
    }

    for(auto& v : arr)
    {
        std::cout << v << std::endl;
    }
}

Godbolt.org

【讨论】:

    【解决方案2】:

    您将循环所有元素并使用stoi 进行转换。 然后将其放入 int-array 中。

    【讨论】:

      猜你喜欢
      • 2018-04-25
      • 1970-01-01
      • 2012-02-26
      • 2016-04-15
      • 2019-04-21
      相关资源
      最近更新 更多