C++ cout cin string manipulation

2019-01-20 16:09发布

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;

2条回答
Emotional °昔
2楼-- · 2019-01-20 16:24
走好不送
3楼-- · 2019-01-20 16:49

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...
}
查看更多
登录 后发表回答