简体   繁体   English

C ++打开文件流

[英]C++ Opening file stream

So i basically need my program to open a file and do something. 所以我基本上需要我的程序打开文件并执行某些操作。 When the program asks for the user to input the file name, and the user inputs the name of file correctly the first time, the operation works. 当程序要求用户输入文件名,并且用户第一次正确输入文件名时,该操作有效。 But if the user typed the name wrong, the program says "invalid name try again" but then it is never able to open the file even if the user types the name correctly. 但是,如果用户输入的名称错误,程序将显示“无效的名称再试一次”,但是即使用户正确输入了名称,它也永远无法打开文件。 Here's the code: 这是代码:

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

What is the problem, any thoughts? 有什么问题吗? Thank you 谢谢

You are redeclaring read_file inside the loop, but the code at the top of the loop always use the read_file outside the loop. 您在循环内重新声明了read_file,但是循环顶部的代码始终在循环外使用read_file。

This is what you want instead: 这是您想要的:

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM