user7228474
user7228474

Reputation:

C++ getline(cin, variable) is misbehaving. No solutions on the site have helped

My code is rather simple. I have a method called promptUserInput that is defined in UtilityFunctions.h; it is implemented in UtilityFunctions.cpp.

My main method includes UtilityFunctions.h. I've correctly written my makefile, and it compiles without issue.

My main method's first line reads:

string input = promptUserInput();

And here's the actual implementation of the promptUserInput function:

/* Prompts user to enter expression */
string promptUserInput()
{
    string userInput;
    cout << "> ";   
    getline(cin, userInput);

    return userInput;
}

But when the program runs, it doesn't display the > symbol. Instead, there's an empty line waiting for user input. I enter some arbitrary character, hit Enter, and the > symbol appears afterwards. None of this makes sense to me. What's going on?

Upvotes: 0

Views: 97

Answers (1)

dtell
dtell

Reputation: 2568

std::cout uses buffered output, which should always be flushed. You can achieve this by using std::cout.flush() or std::cout << std::flush.

You can also use std::cout << std::endl, which writes a line break and then flushes, but the line break might not satisfy your intention.

Upvotes: 2

Related Questions