【问题标题】:How do I correctly use "getline(cin, input);"如何正确使用“getline(cin, input);”
【发布时间】:2016-02-07 19:15:27
【问题描述】:

我正在编写一个程序来转换用户提供的文本。我已经在测试程序中单独尝试了这种方法,并且效果很好;但是,当我尝试将其实现到更大的程序中时,用户无法为程序提供要存储的输入。相关代码如下:

int main()
{
    string str = "NULL";
    int mappings = 0;
    readMappings(mappings);
    receiveInput(str);
    displayInput(mappings, str);
    return 0;
}
void readMappings(int &count)
{
    ifstream readMappings;                                                  // Creates the function "readMappings"
    string filename;                                                        // Generates the filename variable to search for mapping document
    cout << "Enter the filename of the mapping document: ";
    cin >> filename;                                                        // User enters filename
    readMappings.open(filename);                                            // "readMappings" function opens the given mappings document
    while (!readMappings.is_open())
    {
        cout << "Unsble to open file. Please enter a valid filename: ";     // If the user enters an invaled filename, the program will ask again
        cin >> filename;
        readMappings.open(filename);
    }   
    if (readMappings.good())                                                // Mapping document is successfully opened
    {
        readMappings >> count;                                              // Reads first line
    }
    readMappings.close();                                                   // If everything fails in this function, the document will close
}
void receiveInput(string &input)
{
    char correctness;
    do {
        cout << "\nPlease enter the text you would like to be converted to NATO:\n";
        getline(cin, input);
        cout << "You are about to convert: \"" << input << "\".\nIs this correct? (Y/N)" << endl;
        cin >> correctness;
    } while (correctness == 'N' || correctness =='n');
}

我认为可能是程序在等待用户的另一个输入,所以我添加了一个变量,我认为它已经填充了,但它并没有解决我的解决方案。在我看来,问题出在 receiveInput 函数中,但我可能是错的。提前感谢您的任何帮助。

另外,我正在使用具有正确引用变量的函数原型。

【问题讨论】:

标签: c++ input storage getline


【解决方案1】:

我看到两个问题:

1) 在调用 std::getline() 之后,您没有检查 EOF 条件。

2) 您将std::getline&gt;&gt; 运算符混合在一起。现在,这实际上在技术上没有任何问题,但是std::getline&gt;&gt; 运算符都有非常细微的语义,当涉及到错误检查和输入消耗时,你需要得到 100%是的,为了正确地一起使用它们。

只需将&gt;&gt; 运算符的用法替换为std::getline,这样您就只能使用std::getline,并确保检查fail() 或eof()。您将在 stackoverflow.com 上找到大量有关如何正确检查文件结尾和失败条件的示例,std::getline

【讨论】:

  • 能否更详细地解释您的意思只需将&gt;&gt; 运算符的用法替换为std::getline?您指的是getline(cin, input); 行吗?
  • 我通常是认真的。当我说用 std::getline 替换“>> 运算符”时,显然我指的是 >> 运算符,而不是对 std::getline() 的现有调用。在显示的代码中只有一个函数同时使用两者,这就是我所说的“将 std::getline 和 >> 运算符混合在一起”。
猜你喜欢
  • 2013-10-16
  • 2014-04-21
  • 1970-01-01
  • 2014-02-25
  • 1970-01-01
  • 2019-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多