有没有一种方法可以让用户同时输入多个字符数组c++

Is there a way to have user input multiple char arrays at once c++

本文关键字:输入 c++ 数组 字符 用户 一种 方法 有没有      更新时间:2023-10-16

我目前有一个函数,它接受一个由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_indexname_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个,它也会正确调整大小。