[英]Adding elements to an array in C++
我的代码接受输入(本质上是整数的str)
input: 123 456 789 90
我试图将每个数字,例如123
456
等,并将它们添加到数组的一个元素中,但是我不确定如何添加整个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;
}
我知道我的代码做什么,这是不正确的,但这就是我现在所拥有的。 我希望我的数组在返回时最后看起来像这样。
[123] [456] [789] [90] each [] denoting an element/cell.
我知道如何将str转换为int,但是主要的焦点是[1] [2] [3] [4] [5]
而不是每个单元格/元素,如何使它像上面一样显示。 谢谢
您需要使用atoi()
方法将char数组(字符串)转换为int。
arr[n] = atoi(string[i])
我只是使用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;
}
您可以尝试这样的操作。使用字符串流来实现此目的。将字符串拆分为整数
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.