1

我正在尝试从命令行获取一行作为输入。我的问题是我没有得到整条线,但它被空间标记了。

因此,如果我输入诸如“我非常喜欢数学”之类的内容,而不是

"you enterend: I like Math a lot"

我得到以下信息:

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;
4

2 回答 2

12

std::getline是一次读取一行输入的标准方法。

你可以像这样使用它:

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

它返回对具有隐式转换的输入流的引用,void*因此您可以像这样轻松检查成功:

if (std::getline(std::cin, string))
{
    // successfully read a line...
}
于 2009-11-15T00:16:23.257 回答
1

cin.getline(input);

有关更多信息,请参阅http://www.cplusplus.com/reference/iostream/istream/getline/

于 2009-11-15T00:16:58.523 回答