ifstream is.open()表现得好像没有读取文件

问题描述 投票:0回答:2
//Prompts user for a file name and stores it
string fileName;

cout << "Enter the file name: ";
cin >> fileName;

ifstream inFile (fileName);
inFile.open(fileName);

//Prompt the user until they give the name of a file that can be opened
bool validFileName = false;
while(validFileName == false)
{
    if(inFile.is_open())
    {
        validFileName = true;
    }
    else
    {
        cout << "Please enter a valid file name: ";
        cin >> fileName;

        ifstream inFile;
        inFile.open(fileName);
    }
 }
//this block prints to the terminal, so it's opening
 if(inFile.is_open())
 { cout << "It works! \n"; }

我正在尝试创建一个可以处理文件的程序,但是需要有一个部分来检查用户输入的文件是否是程序可以打开的实际文件。我尝试了几种不同的方法来编写while循环,因为它需要不断询问,直到它收到一个有效的文件。我有有效的文件名“input.txt”,但即使我在终端中键入它,它仍继续打印错误消息。我曾尝试使用和不使用引号键入文件名,因此我不确定它是什么。我知道它正在打开文件,因为我之后添加了第二次检查,看起来它正在打开,所以我认为这是一个问题,我如何编写错误检查语句?

c++ fstream
2个回答
2
投票

问题是你正在使用

ifstream inFile;
inFile.open(fileName);

在循环。循环中的变量在循环外部隐藏同名变量。删除第一行。


FWIW,您可以将代码简化为:

ifstream inFile (fileName);

while(!inFile)
{
   // Prompt the user until they give the name of a file that can be opened
   cout << "Please enter a valid file name: ";
   cin >> fileName;

   inFile.open(fileName);
}

if(inFile)
{
   cout << "It works! \n";
}

0
投票

在:

ifstream inFile (fileName);
inFile.open(fileName);

该文件在第一行打开。重新开放是多余的。

同样在循环中,您将声明一个临时变量inFile,该变量在else语句结束时停止。确保在您想要使用它的最外层范围内仅声明一次。

© www.soinside.com 2019 - 2024. All rights reserved.