nav*_*8tr -1 c++ recursion file input
我有用于输入文件并将内容存储在字符串中的函数.
这是代码
std::string inputFile();
int main()
{
std::string fileContents = inputFile();
}
std::string inputFile()
{
std::string fileName;
std::cout << "\nEnter file name, including path:\n";
std::getline(std::cin, fileName);
std::ifstream input(fileName.c_str());
std::string buffer;
std::string result;
if (!input.fail()) // if input does not fail
{
while (!input.eof())
{
std::getline(input, buffer);
result.append(buffer);
}
input.close();
return result;
}
else
{
std::cout << "\nInvalid file name or path";
inputFile(); // recursive call to inputFile
}
}
Run Code Online (Sandbox Code Playgroud)
如果正确输入文件名和路径,它工作正常.
但是,如果输入的文件名或路径不正确,则会执行对inputFile的递归调用,并为用户提供另一个输入文件的机会.然后,如果正确输入文件名,则Visual Studio 2013中会引发错误:
"Assignment4.exe中0x77F7A9E8(msvcr120d.dll)的未处理异常:0xC0000005:访问冲突读取位置0xCCCCCCC0."
谢谢你的任何建议
您有未定义的行为,因为else您没有返回任何内容.
此外,这可能更好地处理循环而不是递归.
顺便说一句,你不应该这样做while (!input.eof()) ...,它不会像你期望的那样工作.原因是在输入操作失败之前未设置EOF标志,因此您将在输入操作失败之前检查您是否已到达文件末尾.
解决方案是使用std::getline返回流的事实,并且流对象可以用作布尔值来检查一切正常:
while (std::getline(...)) { ... }
Run Code Online (Sandbox Code Playgroud)