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.
编辑:另外,请记住,仅分配 4 个字符input
并不能说明将在末尾添加的字符串字符'\0'
的结尾。如果用户输入 4 个字符,那么它在将字符串分配给您的input
. 有 4 个字符 + 1 个结束字符,这意味着您至少需要为input
. 最好的方法是使用std::string
它,因为即使用户输入超过 4 个字符,它也会正确调整大小。