干扰GETLINE功能的东西



我是代码和本网站的新手,所以如果我忽略了明显的东西,请原谅我。我一直在尝试在C 中写一个简短的小游戏,我需要接受用户输入。我想接管多个单词,因此我的书建议的cin>>命令是正确的。我通过研究发现的最好的东西是getline(cin,var);命令。我可以让它轻松地在小型测试中工作,但是当我将其实现到500行游戏中时,它永远无法使用。它将跳过这一点代码,而无需等待用户封装,并将变量设置为空白。我显然不会包括整个代码,但这是有问题的,我的标题。

#include <cstdlib>
#include <windows.h>
#include <iostream>
#include <string>
using namespace std;
string poemend;
int heading;  
int poem()
{
    system("CLS");
    cout<<"This  poem is almost done, you just can't seem to find the perfect last word.n";
    cout<<"You can see several of your discarded endings. Most recently, 'pain'.nn";
    cout<<"How about another go?n>";
    getline(cin,poemend);
    system("CLS");
    cout<<"The Prophet's old parrot spoke much of all things,n";
    cout<<"but when asked about love, squawked only ";
    cout<<poemend<<" .nn";
    Sleep(6000);
    cout<<"You decide it could still use some work";
    Sleep(3000);
    heading = 6;
}

再次,如果我将其输入新的空白页面,这非常有效,因此我真的不确定会发生什么。我很乐意回答有关代码的任何问题,并在需要时发布更多有用的位置。非常感谢您抽出宝贵的时间阅读!

有时会冲洗输入缓冲区是魔术。在您的senario中可能是也可能不是这种情况,但请尝试此代码。

cin.ignore( cin.rdbuf()->in_avail() );
cin.getline(cin,poemend);
cin.clear();

本质上,用忽略代码和cin.clear将getline包裹。

您仍然有一个newline,它是先前未形成的输入操作的残基。您必须使用std::ws丢弃它。此外,始终检查您的输入是否成功:

if (std::getline(std::cin >> std::ws, poemend))
//               ^^^^^^^^^^^^^^^^^^^