为什么我不能继续使用 std::cin 向同一个变量输入其他值?

Why I can't proceed to enter other values to the same variable with std::cin?

当我为 group_input 变量输入值时,程序结束,我无法为 fio_input 变量输入值。如果我输入一个短值,我可以继续为 fio_input 变量输入一个值。有什么问题?

#include <iostream>
using namespace std;

int main()
{
    unsigned char group_input, fio_input, result[7] = {0, 0, 0, 0, 0, 0, 0};

    cout << "\n    Enter your group name: ";
    cin >> group_input;
    cout << "\n    Enter your full name: ";
    cin >> fio_input;
}

在这一行

cin >> group_input;

您从标准输入读取并将结果写入 unsigned char 变量。将读取多少字节?这取决于上面一行调用的重载 operator >> 。在你的例子中,"input lines" 都调用了 unsigned char 的重载,因为这种数据类型只能存储一个字节,它读取一个字节。因此,您可以为两个变量输入一个字符的名称,或者将 group_inputfio_input 的数据类型更改为其他类型,例如std::string。在这种情况下,调用 operator >> 重载读取任何内容直到下一个空白(但不包括它)字节,其中 "whitespace byte" 包括制表符、换行符等

当您读入char个变量时,系统会读入个字符。而单个char只能存储一个字符,所以读取的就是这个。

如果您输入多字符,那么第一个字符将存储在 group_input 中,第二个字符将存储在 fio_input 中。

如果你想读取字符串(这似乎是你想要的)然后使用 std::string.

如果您想避免缓冲区溢出,使用 std::string 尤为重要。 C++ 没有数组的边界检查。

您要的是一个名称,它是 char 的数组 - 一个 std::string.

#include <iostream>
#include <string>

int main(){
    std::string group_input, fio_input;

    std::cout << "\n    Enter your group name: ";
    std::cin >> group_input;
    std::cout << "\n    Enter your full name: ";
    std::cin >> fio_input;
}

你不应该使用 use namespace std; 阅读 here 为什么。

此外,如果您想输入带空格的名称,请改用 std::getline(std::cin, str);。因为如果你 std::cin "Roger Jones"fio_input 它只会节省 "Roger"