Pregunta

I'm new to code and this website, so please forgive me if I'm overlooking something obvious. I've been trying to write a short little game in c++, and I need to take in user input. I want to take in more than one word so the cin>> command my book recommends is right out. The best thing I have found through research is the getline(cin,var); command. I can get this to easily work in small scale tests, but when I implement it in to my 500 line game, it never works. It will skip right over that bit of code without waiting for user imput, and set the variable to a blank space. I won't include the whole code obviously, but here is the bit in question, and my headers.

#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'.\n\n";
    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<<" .\n\n";
    Sleep(6000);
    cout<<"You decide it could still use some work";
    Sleep(3000);
    heading = 6;
}

Again, this works perfectly if I take this in to a new blank page, so I'm really not sure what is getting in the way. I will be happy to answer any questions about the code and post more helpful bits of it if needed. Thank you so much for taking the time to read this!

¿Fue útil?

Solución

Sometimes flushing the input buffer is magic. This may or may not be the case in your senario, but try this code.

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

Essentially wrapping your getline with the ignore code and cin.clear.

Otros consejos

You still have a newline which is the residue of a previous unformatted input operation. You have to discard it using std::ws. Moreover, always check if your input succeeded:

if (std::getline(std::cin >> std::ws, poemend))
//               ^^^^^^^^^^^^^^^^^^^
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top