我正在编写一个程序,用于转换用户给出的文本。我已经在测试程序中单独尝试了这种方法,它运行良好;但是,当我尝试将其实现到更大的程序中时,用户无法为程序提供要存储的输入。相关代码如下:
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');
}
我认为可能是程序在等待用户的另一个输入,所以我添加了一个我认为它已经填充的变量,但它没有修复我的解决方案。 在我看来,问题出在接收输入函数上,但我可能是错的。 提前感谢任何帮助。
此外,我正在使用具有正确引用变量的函数原型。
我看到两个问题:
1) 在调用 EOF 后,您没有检查 EOF 条件std::getline()
。
2)您将std::getline
和>>
运算符混合在一起。现在,这在技术上实际上没有任何问题,但是std::getline
和>>
运算符都有非常细微的语义,当涉及到错误检查和输入消耗时,你需要得到100%正确,以便正确地将它们一起使用。
只需将>>
运算符的用法替换为 std::getline
,以便您专门使用 std::getline
,并确保检查 fail
() 或 eof
()。您将找到大量有关如何正确检查文件结束和失败条件的示例,std::getline
,请参阅 stackoverflow.com。