【问题标题】:C++ cout cin string manipulationC++ cout cin 字符串操作
【发布时间】:2009-11-15 00:14:20
【问题描述】:

我正在尝试从命令行获取一行作为输入。我的问题是我没有得到整行,而是被空格标记。

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

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

【问题讨论】:

    标签: c++ string cout cin


    【解决方案1】:

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

    你可以这样使用它:

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

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

    if (std::getline(std::cin, string))
    {
        // successfully read a line...
    }
    

    【讨论】:

    • 如果你想接收一个 c 字符串,不要忘记 cin.getline(char*, int) 版本。
    • 它没有显式转换为 void*。它具有到可在布尔上下文中使用的未指定类型的显式转换。在您的实现中它可能碰巧是 void* ,但这可能并不适用于所有情况。而且它更容易向初学者解释结果可以转换为类似于布尔值的东西。
    • 其实operator void*是标准要求的。它是basic_ios 基类接口的一部分。
    【解决方案2】:

    cin.getline(input);

    请参阅http://www.cplusplus.com/reference/iostream/istream/getline/ 了解更多信息。

    【讨论】:

    • 称为getlineistream 成员函数都采用char 缓冲区和长度,而不是string
    • 我已经尝试过了,问题是由于代码处于while循环中,首先它会读取换行符。所以当我什至什么都不输入时,我总是得到“你输入了”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-13
    相关资源
    最近更新 更多