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

问题描述 投票:-1回答:3

当我输入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;
}
c++ cin
3个回答
2
投票

你要的是一个名字,这是一个chars阵列 - 一个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"


2
投票

当您读入char变量时,系统将读取字符。而单个char只能存储一个字符,因此这将是读取的内容。

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

如果你想读取字符串(这似乎是你想要的),那么使用std::string

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


1
投票

在这一行

cin >> group_input;

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

© www.soinside.com 2019 - 2024. All rights reserved.