将用户输入追加到C++数组
Append user input to array in C++
我正在尝试编写一个程序,要求用户输入(一次一个,并持续到用户以某种方式中断)并将它们存储在数组中。在python中,我可以轻松地将新输入附加到现有列表的末尾,但这在C++中不起作用。在不涉及向量的情况下做到这一点的最简单方法是什么?我正在考虑每次都删除数组并创建一个更大的新数组,但这似乎很痛苦。
这是我为此编写的一些代码,它基本上创建了一个新数组并从旧数组中复制数据。希望这可以帮助您。为了给您一个用法示例,有一个演示区域,它从 stdin 输入数据,直到用户键入"END"并将其打印到 stdout,不包括"END"。
#include <cstdio>
#include <iostream>
#include <cstring>
//Assuming you are storing strings
//Set this to the appropriate max length. The name of this may be misleading,
const int MAX_STRING_LENGTH = 128; //any other suggestions?
char** userInput;
int userInputUsed;
int userInputSize;
void append (char* text, int textLength) {
//If we have used up all the space in the array
if (userInputUsed >= userInputSize) {
//How large you want the new array to be compared to
//the original size (userInputSize)
int newArraySize = 2*userInputSize;
//Create the new array
char** newUserInput = new char*[newArraySize];
//We are only creating the new part of the array
//Another way you could do this is to create the strings as you go
for (int i = userInputUsed;i < newArraySize;i++) {
newUserInput[i] = new char[MAX_STRING_LENGTH];
}
//Copy everything over, I am setting our pointers to the old data
for (int i = 0;i < userInputUsed;i++) {
newUserInput[i] = userInput[i];
}
//Delete the old array
delete[] userInput;
//Set the new array to the old array
userInput = newUserInput;
//Update the size of our array;
userInputSize = newArraySize;
}
//Copy the input to userInput
memcpy(userInput[userInputUsed], text, textLength);
userInputUsed++;
}
int main () {
//Initialise userInput, initialise to whatever size you deem fit
userInputSize = 1;
userInput = new char*[userInputSize];
for (int i = 0;i < userInputSize;i++) {
userInput[i] = new char[MAX_STRING_LENGTH];
}
//Start of demonstration
//Get input until the user types "END"
for (bool running = true;running;) {
char temp[MAX_STRING_LENGTH];
//Scans in until some whitespace, this may not work if
//you want to scan in whole lines which end in 'n'
//scanf("%s", temp);
//or
std::cin >> temp;
//End if input is "END"
if (strcmp(temp, "END") == 0) {
running = false;
} else {
append(temp, strlen(temp));
}
}
//Print out the user input, to see that it is inputed correctly
for (int i = 0;i < userInputUsed;i++) {
//printf("%sn", userInput[i]);
//or
std::cout << userInput[i] << std::endl;
}
//End of demonstration
//Cleanup our user input
for (int i = 0;i < userInputSize;i++) {
delete[] userInput[i];
}
delete[] userInput;
//Stop the program from ending, you may not need this
//while(true);
return 0;
}
请随时对此答案发表评论或提出改进建议。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '