在C ++中向数组添加元素

时间:2014-11-05 05:41:44

标签: c++ arrays pointers dynamic

我的代码接受输入(本质上是str)

  input: 123 456 789 90  

我尝试将123 456等各个号码添加到我的阵列的一个元素中,但我不确定如何添加整个{ {1}}。

123

我知道我的代码做了什么而且它不正确,但这就是我现在所拥有的。我希望我的数组在返回时最终看起来像这样。

some_int represents the number of ints. So in this case, it would be 4   

int* arr_func(int some_int)
{
  std::string str;
  std::getline (std::cin, str);
  int* p = new arr[some_int];
  for (i=0;i<str.length(),++i)
  { 
  if (str[i] != ' ')
    {
    arr[n] = str[i];
    }
  }
  return p;
}    

我知道如何将str转换为int,但主要关注的不是每个单元格/元素都是[123] [456] [789] [90] each [] denoting an element/cell. ,我如何才能使它如上所示。 感谢

4 个答案:

答案 0 :(得分:0)

您需要使用atoi()方法将char数组(字符串)转换为int。

arr[n] = atoi(string[i])

答案 1 :(得分:0)

我不想给你完整的答案,但我会告诉你如何解决这个问题。

首先,您需要使用可以学习here的空格来分割输入。

您还需要创建一个动态数组,如下所示:

int* input = new int[some_int];

之后使用像

这样的for循环
for(int i = 0 ; i<some_int ; i++){
    //some code here
}

在上面的注释区域中使用atoi()函数将char *转换为整数,您可以看到样本here

答案 2 :(得分:0)

我只是使用std::cin代替std::getline

另外,AFAIK,当你分配内存时,你应该释放它;
返回指针并将责任留给调用者,这不是最好的主意,
因为很容易忘记释放内存,导致内存泄漏。

我改用std::vector。或者,您可以使用某种智能指针,但我不会告诉您如何使用它,因为我根本就不知道。

我写道:

#include <iostream>
#include <vector>

std::vector<int> arr_func(const unsigned length) {
    std::vector<int> result;
    result.reserve(length); //optimization, can be skipped
    for(unsigned i=0; i<length; ++i) {
        int temp;
        std::cin >> temp;
        result.push_back(temp);
    }
    return result;
}

/* Other solution, may be less efficent */

std::vector<int> arr_func(const unsigned length) {
    std::vector result(length);
    for(auto& i:result)
        std::cin >> i;
    return result;
}

答案 3 :(得分:-1)

你可以尝试这样的事情。使用字符串流来实现这一点。将字符串分成整数

#include<sstream>
#include <iostream>
using namespace std;

int main() {
    stringstream stream;
    string str="123 456 789";
    stream <<str;
    int n[3];
    for(int i=0;i<2;i++){
    stream >> n[i];}
    cout<<n[0]<<endl<<n[1]<<endl<<n[2];
    return 0;
}