0

在程序读取文件、从文件中获取字符并完成后,会询问用户是否要读取另一个文件。如果用户说是,那么程序会询问文件名,但随后会自动说文件无法打开并退出循环。请帮我。

这是代码:

do //do while opening the source file fails
      {
         cout << "Enter filename of source file: ";
         cin.getline (filename,51);
         sourceFile.open(filename);  //opens the file with given filename
         if (sourceFile.fail())
            cout << "File could not be opened" << endl;  //error if can't open
         sourceFile.clear();
      } 
      while (sourceFile.fail());  //exits if source file doesn't fail
4

2 回答 2

1

本次测试:

while (sourceFile.fail())

永远不会是真的,因为就在你到达那里之前,你打电话:

sourceFile.clear()

这将清除流中的任何问题位iostate

我想你只是想摆脱对clear().

于 2012-03-21T03:38:46.633 回答
0

检查打开文件是否失败的规范方法是使用std::basic_ios::operator !()

do
{
    cout << "Enter filename of source file: ";
    std::getline(std::cin, filename);
    sourceFile.open(filename.c_str());
    if (!sourceFile)
    {
        cout << "File could not be opened" << endl;
    }
}
while (!sourceFile);
于 2012-04-27T05:27:50.200 回答