[英]My while loops seems to be ignoring my getline
Here's all the code 这是所有代码
#include <iostream>
#include <string>
#include <windows.h>
#include <stdlib.h>
using namespace std;
void Pdelay(string str)
{
for (char c : str)
{
std::cout << "" << c << "";
Sleep(100);
}
std::cout << '\n';
}
int main()
{
int exit = 1;
while (exit == 1)
{
cout<< "Type something\n:";
string str;
str.clear();
getline(cin,str);
Pdelay(str);
cout << "\n\n[1]Type something again"<< endl;
cout << "[2]Exit\n:";
cin >> exit;
}
return 0;
}
Whenever I run it, it works properly the first time round, when it loops back it skips the getline and continues with the two cout statements. 每当我运行它时,它都会在第一轮正常运行,当它循环返回时,它将跳过getline并继续执行两个cout语句。
Immediately after you use cin
, the newline remains in the buffer and is being "eaten" by the subsequent getline
. 使用cin
,换行符会立即保留在缓冲区中,并被后续的getline
“吃掉”。 You need to clear the buffer of that additional newline: 您需要清除该附加换行符的缓冲区:
// immediately after cin (need to #include <limits>)
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
That's why it's not a very good idea to combine std::cin
and std::getline
. 这就是为什么将std::cin
和std::getline
结合起来不是一个好主意的原因。 BTW, you can write your code in fully standard compliant C++11, with no additional non-library headers: 顺便说一句,您可以使用完全符合标准的C ++ 11编写代码,而无需其他非库头文件:
#include <chrono>
#include <iostream>
#include <limits>
#include <string>
#include <thread>
void Pdelay(std::string str)
{
for (char c : str)
{
std::cout << "" << c << "" << std::flush;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
std::cout << '\n';
}
int main()
{
int ext = 1;
while (ext == 1)
{
std::cout << "Type something\n:";
std::string str;
str.clear();
std::getline(std::cin, str);
Pdelay(str);
std::cout << "\n\n[1]Type something again" << std::endl;
std::cout << "[2]Exit\n:";
std::cin >> ext;
if(!std::cin) // extraction failed
{
std::cin.clear(); // clear the stream
ext = 1;
}
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
}
I just realized that this question has been asked (in a slightly modified form) before, and the answers are great: 我刚刚意识到,以前曾有人问过这个问题(形式稍有修改),答案很好:
Why does std::getline() skip input after a formatted extraction? 为什么std :: getline()在格式化提取后会跳过输入?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.