在循环中使用cin函数有问题

Having issue with cin function in a loop

本文关键字:cin 函数 有问题 循环      更新时间:2023-10-16

我只是想用循环填充字符串数组。我的问题是,当它进入循环输入名称时,它将立即为向量中的第一个槽输入空白行。为什么会发生这种情况?我该怎么补救呢?请不要介意我缺乏代码风格,我是一个新手,我想在这个冬天开始上课之前重新获得我的编程知识…

下面是一些示例输出:

How many people are in your family?
4
Please enter the names of all of your family members
check name:
Please enter the names of all of your family members
Matt
check name:Matt
Please enter the names of all of your family members
Evan
check name:Evan
Please enter the names of all of your family members
Michelle
check name:Michelle
Matt
Evan
Michelle

,这是我的代码:

vector<string> Names;
bool complete=0;
while(!complete)
{
    int number;
    cout << "How many people are in your family?" << endl;
    cin >> number;
    for(int i=0; i<number; i++)
    {
        string names;
        cin.clear();
        cout << "Please enter the names of all of your family members" << endl;
        getline(cin,names);
        Names.push_back(names);
        cout << "check name:" << names << endl;
    }
    complete = 1;
}
for (int i=0; i< Names.size(); i++)
{
    cout << Names[i] << endl;
}

您看到这种行为的原因是将>>读取与getline混合在一起。当读取计数时,输入指针向前移动到数字输入的末尾,即4,并在读取新的行字符之前停止。

这是当你调用getline;读取新的行字符,并立即返回新的行。

解决方法:在cin >> number呼叫后再呼叫getline,并丢弃呼叫结果

我建议你试试

std::cin >> names;

代替

getline(std::cin, names);

getline从std::cout打印字符串中获取std::endln。这个想法是getline将读取到n字符(这是一个结束符的指示),但它也将消耗结束符。这就是为什么它在vector中使用换行符的原因。

考虑这样做…

std::cin.get();

将读取std::endl字符,然后使用getline函数

问题是将带字体的输入(std::cin >> number)与未格式化的输入(std::getline(std::cin, names))混合在一起。格式化的输入在第一个非整数字符处停止,很可能是在计数后输入的换行符。最简单的修复方法是显式跳过前导空格:

std::getline(std::cin >> std::ws, names);

注意,您还需要在每次输入后检查它是否成功:

if (std::cin >> number) {
    // do something after a successful read
}