在C++中添加元素到数组中
我的代码本质上接受int的inputstr在C++中添加元素到数组中,c++,arrays,pointers,dynamic,C++,Arrays,Pointers,Dynamic,我的代码本质上接受int的inputstr input: 123 456 789 90 我试图将每个数字(如123456等)添加到数组的一个元素中,但我不确定如何添加整个123 我知道如何将str转换为int,但主要关注点不是每个单元格/元素都是[1][2][3][4][5],而是如何使其看起来像上面那样。 谢谢您需要使用atoi方法将字符数组字符串转换为int arr[n] = atoi(string[i]) 您可以尝试以下操作。使用字符串流来实现此操作。将字符串拆分为整数 #in
input: 123 456 789 90
我试图将每个数字(如123456等)添加到数组的一个元素中,但我不确定如何添加整个123
我知道如何将str转换为int,但主要关注点不是每个单元格/元素都是[1][2][3][4][5],而是如何使其看起来像上面那样。
谢谢您需要使用atoi方法将字符数组字符串转换为int
arr[n] = atoi(string[i])
您可以尝试以下操作。使用字符串流来实现此操作。将字符串拆分为整数
#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;
}
我不想给你完整的答案,但我会告诉你如何解决这个问题 首先,您需要使用可以学习的空格分割输入 您还需要创建动态数组,如下所示:
int* input = new int[some_int];
之后,使用for循环,如
for(int i = 0 ; i<some_int ; i++){
//some code here
}
在上面的注释区域中,使用atoi函数将char*转换为整数,您可以看到示例。我只需使用std::cin而不是std::getline
另外,好吧,当你释放内存时,你应该释放它;
返回指针并将释放指针的责任留给调用方这不是最好的主意,
因为很容易忘记释放内存,这会导致内存泄漏
我会使用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;
}
首先尝试修复语法。dinamic数组是使用关键字new创建的,函数应该返回一些内容。其次,你没有传递字符串。第三,string和integer不同,您应该使用stoi plus,在将其拆分为单词之前,您可以使用stringstream,因为int i=0;我!=str.length++我将从检查语法错误开始。int*p=newint[some_int];您可以使用std::vector代替原始指针int*@Justin ssin在库sstream中,第一个链接中的答案是正确工作,请参阅运行版本:您能快速解释while循环吗。我一直想弄明白,但似乎弄不明白..特别是ssin>>arr[I]的作用以及它如何使每个元素成为一个单词。同样在我的情况下,我需要将str更改为int,然后将其添加到while循环中的数组中,对吗?@Justin good没什么特别的,只要读取并检查流是否仍然正确!i> arr[i]只是将拆分字符串的第i个元素与arr[i]中的空格放在一起,例如arr[0]=test,arr[1]=one,……这是我不确定的。那么使用ssin只是自动拆分字符串?对于您编写的for循环,我是否会索引数组的指针输入[I]并将其更改为int?所以这就像输入[i]=atoiinput[i]?@Justin输入[i]=atoiinput[i]没有意义,输入中必须有一个字符*从我给你的例子中了解atoi;
for(int i = 0 ; i<some_int ; i++){
//some code here
}
#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;
}