在循环中使用cin函数有问题
Having issue with cin function in a loop
我只是想用循环填充字符串数组。我的问题是,当它进入循环输入名称时,它将立即为向量中的第一个槽输入空白行。为什么会发生这种情况?我该怎么补救呢?请不要介意我缺乏代码风格,我是一个新手,我想在这个冬天开始上课之前重新获得我的编程知识…
下面是一些示例输出:
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::endl
或n
。这个想法是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
}
相关文章:
- C++中的cin.ignore()函数不适用于整个流
- C++输入流.与 cin unget() 函数有点混淆
- 如何在C++中将 cin 设置为类的成员函数?
- 如何将 std::cin 作为函数的参数传递?
- cin.get()函数在C 中
- 如何使用std::cin函数后修复从文件读取的问题
- Cin和Cout在构造函数中
- 如何将 cin 传递给函数
- 与 CIN 一起使用的 getline() 函数
- CIN.IGNORE删除第一个字符的第二次函数被调用
- 将GoogleTest与通过STD :: CIN从用户输入的函数一起使用
- 运行时对cin函数的混淆
- cin函数是否添加了在输入结束时终止的null
- CIN函数不显示本地回声
- 使用cin函数
- 未知类型的 CIN >>函数模板参数
- 使用 CIN 函数在 C++ 中输入数学运算
- 挣扎与cin函数c++
- 在循环中使用cin函数有问题
- 关于cin函数到一个对象的所有公共成员