有没有一种方法可以让用户同时输入多个字符数组c++
Is there a way to have user input multiple char arrays at once c++
我目前有一个函数,它接受一个由4个字符组成的数组,并根据该字符序列返回另一个值。
我想要的是让用户输入一整行字符,然后创建一个循环来遍历每个"字符子组",然后返回所有字符的结果。
我最初的想法是以某种方式使用push_back将数组不断添加到向量中。
我不知道整个数组会有多长,但它应该是3的乘积。
举个例子,现在我可以做:
char input [4] ;
cin >> input;
int i = name_index[name_number(input)];
cout << name[i].fullName;
但我希望用户一次输入多个名称缩写
我会将您的样本更改为:
char input [4] ;
cin >> input;
int i = name_index[name_number(input)];
cout << name[i].fullName;
对此:
string input;
cin >> input;
const int i = name_index[name_number(input)];
cout << name[i].fullName;
然后,您可以开始使用矢量来跟踪多个输入:
vector<string> inputs;
string line;
while (cin >> line)
{
if (line == "done")
break;
inputs.push_back(line);
}
for (unsigned int i = 0; i < inputs.size(); ++i)
{
cout << "inputs[" << i << "]: " << inputs[i] << endl;
//const int index = name_index[name_number(inputs[i])];
//cout << name[index].fullName;
}
您要求对line
进行解释。行while (cin >> line)
尝试从标准输入中获取文本并将其放入line
中。默认情况下,当遇到空白(空格、制表符、回车等)时,这将停止。如果成功,则执行while
循环的主体,并将输入的内容添加到vector
。如果不是,那么我们假设我们已经结束了输入并停止。然后我们可以处理vector
。(在下面链接的代码中,我只是输出它,因为我不知道name_index
或name_number
是什么。
(此处为工作代码)
cin的工作方式是,它将接受任何数量的输入,并用空格将它们分开,当你要求特定的输入时,它会提示用户输入,然后只接受第一个字符串(直到空格)。如果之后还有任何输入,另一个cin >> input
将只检索该值,而不会再次提示用户。当只剩下换行符时,您可以判断何时到达输入的实际末尾。这个代码应该允许您键入多个用空格分隔的字符串,然后在用户输入文本后一次处理所有字符串:
char input[4];
do // Start our loop here.
{
// Our very first time entering here, it will prompt the user for input.
// Here the user can enter multiple 4 character strings separated by spaces.
// On each loop after the first, it will pull the next set of 4 characters that
// are still remaining from our last input and use it without prompting the user
// again for more input.
// Once we run out of input, calling this again will prompt the user for more
// input again. To prevent this, at the end of this loop we bail out if we
// have come accros the end of our input stream.
cin >> input;
// input will be filled with each 4 character string each time we get here.
int i = name_index[name_number(input)];
cout << name[i].fullName;
} while (cin.peek() != 'n'); // We infinitely loop until we reach the newline character.
编辑:此外,请记住,仅为input
分配4个字符并不能说明将附加在末尾的字符串' '
的末尾。如果用户输入了4个字符,那么当它将字符串分配给input
时,它实际上会访问坏内存。共有4个字符+1个结束字符,这意味着您至少需要为input
分配5个字符。最好的方法是只使用std::string
,因为即使用户输入的字符超过4个,它也会正确调整大小。
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 2D数组来自文本输入,中间有空格
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 检查输入是否不是整数或数字
- 正在尝试了解输入验证循环
- 读取文件并输入到矢量中
- C++如何通过用户输入删除列表元素
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 用户定义函数中的指针和输入
- 如何在C++中检查2D数组中负值的输入验证
- 如何只允许用户输入正整数
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 输入中的字符串数未知(以字母表示)
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 在一个模板函数中,若输入的类型是enum类,我该如何使用std::underlying_type