2012-02-06 67 views
0

所以我基本上需要我的程序打开一个文件并做一些事情。当程序要求用户输入文件名,并且用户第一次正确输入文件名时,该操作就起作用。但是,如果用户输入了错误的名称,程序会显示“无效名称再次尝试”,但即使用户正确输入名称,也永远无法打开该文件。这里的代码:C++打开文件流

ifstream read_file(file.c_str()); 
while(true) 
{ 
    if(!(read_file.fail())) 
    { 
     ... 
    } 
    else 
    { 
     cout << "Either the file doesn't exist or the formatting of the file is incorrect. Try again.\n>"; 
    } 
    cin >> file; 
    ifstream read_file(file.c_str()); 
} 

什么问题,有什么想法?谢谢

回答

5

您将在循环内重新声明read_file,但循环顶部的代码始终使用循环外部的read_file。

这是你想要什么,而不是:

ifstream read_file(file.c_str()); 
while(true) 
{ 
    if(!(read_file.fail())) 
    { 
     ... 
    } 
    else 
    { 
     cout << "Either the file doesn't exist or the formatting of the file is incorrect. Try again.\n>"; 
    } 
    cin >> file; 
    read_file.open(file.c_str()); /// <<< this has changed 
} 
+0

+1。也许值得注意的是,如果(read_file)等于if(!read_file.fail()) – stinky472 2012-02-06 02:45:27

+0

这个工作,非常感谢你 – Richard 2012-02-06 02:46:22

+0

@stinky谢谢你,但我留下的代码是'因为它更迂腐 – Gigi 2012-02-06 02:49:36