C++ cout cin string manipulation

有些话、适合烂在心里 提交于 2019-11-27 08:33:16

问题


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;

回答1:


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



回答2:


cin.getline(input);

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



来源:https://stackoverflow.com/questions/1736080/c-cout-cin-string-manipulation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!