2012-03-21 58 views
0

程序读取文件后,从文件中获取字符,并完成后,询问用户是否需要读取其他文件。如果用户说是,那么程序要求提供文件名,但随后会自动说该文件无法打开并退出循环。请帮帮我。C++后续文件在第一个文件后无法打开

下面是代码:

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 
+1

你尝试调试?您试图打开的文件名是否有意义? – 2012-03-21 03:30:29

+0

什么是一个好的调试器? – 2012-03-21 03:32:14

+1

你会得到什么错误?你在哪个系统上运行? 'gdb'是一个流行的调试器,但是你使用的将取决于你使用的是什么系统。 – 2012-03-21 03:33:08

回答

1

这个测试:

while (sourceFile.fail()) 

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

sourceFile.clear() 

这将清除任何问题位在iostate中。

我想你只是想摆脱clear()的电话。

+0

它的工作原理是,第一个文件在运行时通过此循环运行时打开正确 – 2012-03-21 03:43:07

+0

@TylerGavin:我认为问题在于如果打开失败,循环不会再次请求文件名。 – 2012-03-21 03:46:17

+0

@TylerGavin:我想我现在看到了 - 我相信我在这个答案中有一个问题在你的代码中(如果打开失败,你没有机会再试一次,这就是我认为循环的意图是)。然而,听起来你的直接问题是由arminb的评论解决的。 – 2012-03-21 04:02:13

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