首页 文章

在函数中验证文件并在main中调用它,如果有效则输出“file is valid”

提问于
浏览
0

远没有完成,但现在我试图让这个程序要求文件名并将其存储在字符串然后转换为ifstream,然后通过调用单独的函数isValid来检查文件是否有效,如果有效和错误它将返回true如果没有,如果它是有效的,主函数将“文件有效” . 然后它将继续重复此操作,直到输入退出 . 但它每次都会返回false,我不知道出了什么问题 . 我会很乐意为你提供任何帮助 .

# include <iostream>
#include <string>
#include<fstream>
using namespace std;

bool isValid(ifstream& file)
{
    if (file.good())
    {

        return true;
    }
    else
    {
        return false;
    }
}



int main()
{
    string file_name;
    cout <<"please enter a HTML file name or hit 'exit' to quit and if you want to clear file please enter 'clear': ";
    cin >> file_name;
    ifstream my_file(file_name.c_str());



    while (file_name != "exit")
    {
        if ((isValid(my_file)) == true)
        {
            cout << "Hello" << endl;
        }
        string file_name;
        cout <<"please enter a HTML file name or hit 'exit' to quit and if you want to clear file please enter 'clear': ";
        cin >> file_name;
        ifstream my_file(file_name.c_str());
    }
}

1 回答

  • 0

    您遇到了一个名为“阴影”的问题 .

    int main() {
        int i = 0;
        while (i == 0) {
            int i = 1;  // declares a new variable that
            // "shadows" (obscures) the outer i inside this scope
        }  // shadow i goes away, original i returns
    }
    

    上面的代码将永远运行,因为在while循环的上下文中的 i 是在main中声明的 i .

    您的代码执行此操作:

    int main()
    {
        // ...
        ifstream my_file(file_name.c_str());
    
        while (file_name != "exit")
        {
            if ((isValid(my_file)) == true)  // << outer my_file
            // ...
            ifstream my_file(file_name.c_str()); // << scope-local variable
        }  // << scope local my_file goes away
    }
    

    您可能需要考虑重构代码以避免重复并简化它:

    #include <iostream>
    #include <fstream>
    #include <string>
    
    int main() {
        for (;;) {  // infinite loop
            std::string file_name;
            std::cout <<"please enter a HTML file name or hit 'exit' to quit and if you want to clear file please enter 'clear': " << std::flush;
            if (!std::getline(std::cin, file_name))
                break;
            if (file_name == "exit")
                break;
    
            std::ifstream my_file(file_name);
            if (!my_file.is_open()) {
                std::cerr << "unable to open file " << file_name << '\n';
                continue;
            }
    
            std::cout << "hello\n";
        }
    }
    

    我把它作为练习留给你重新介绍你的isValid函数 .

相关问题