开发者

C++ cout cin string manipulation

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
   开发者_StackOverflow     cout << "you entered " << input <<endl;


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...
}


cin.getline(input);

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜