views:

332

answers:

2

I'm trying to get a line as input from the command line. My problem is that I'm not getting the whole line, but it's being tokenized by space.

So if I entered something such as "I like Math a lot" instead of getting

"you enterend: I like Math a lot"

I get the follwoing:

EDITING MODE: Enter a command
i like Math a lot
you entered i

EDITING MODE: Enter a command
you entered like

EDITING MODE: Enter a command
you entered Math

EDITING MODE: Enter a command
you entered a

EDITING MODE: Enter a command
you entered lot


void enterEditingMode(){
    editingMode = TRUE;
    static string CMD = "\nEDITING MODE: Enter a command\n";
    string input;
    while(editingMode == TRUE){
     cout << CMD;
     cin >> input;
     //we assume input is always correct
     // here we need to parse the instruction
     cout << "you entered " << input <<endl;
+10  A: 

std::getline is the standard way to read a line of input at a time.

You can use it like this:

std::getline(std::cin, string);

It returns a reference to the input stream which has an implicit conversion to void* so you can check for success easily like this:

if (std::getline(std::cin, string))
{
    // successfully read a line...
}
Charles Bailey
And don't forget the cin.getline(char*, int) version if you want to take in a c string.
Graphics Noob
It does not have an explicit conversion to void*. It has an explicit conversion to an unspecified type that is usable in a Boolean context. It may happen to be void* in your implementation but that may not hold across all. And its a lot easier to explain to beginners that the result is convertible to something that acts like a boolean.
Martin York
Actually, `operator void*` is required by the standard. It's part of the `basic_ios` base class interface.
Charles Bailey
A: 

cin.getline(input);

See http://www.cplusplus.com/reference/iostream/istream/getline/ for more info.

Stephen Newell
The `istream` member functions called `getline` all take `char` buffers and a length, not a `string`.
Charles Bailey
I tried this already, the problem is that since the code is in a while loop, at first it reads the new line character. So I always get "you entered" when I don't even enter anything.