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

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

本文关键字:变量 输入 其他 cin 不能 继续 std 为什么      更新时间:2023-10-16

当我输入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;
}

您要一个名称,这是 char s -a 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;

另外,如果要输入空格名称,请改用std::getline(std::cin, str);。因为如果您std::cin "Roger Jones"fio_input,它将仅保存"Roger"

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

如果给出多字符输入,则第一个字符将存储在group_input中,第二个字符将存储在fio_input中。

如果您想阅读字符串(这似乎是您想要的),则使用std::string

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

在此行中

cin >> group_input;

您从标准输入中读取并将结果写入unsigned char变量。将读取多少个字节?这取决于上线引用的过载的operator >>。在您的情况下,两个"输入线"都调用了unsigned char的过载,因为此数据类型只能存储一个字节,因此它读取一个字节。因此,您可以为两个变量输入一个字符名称,也可以将group_inputfio_input的数据类型更改为其他内容,例如。std::string。在这种情况下,调用了operator >>超载,将任何内容读取到下一个whitespace(但不包括它)字节,其中" Whitespace Byte"包括Tab,Newline等。