【问题标题】:Validating file in function and calling it in main and outputing "file is valid" if it is valid在函数中验证文件并在 main 中调用它,如果有效则输出“文件有效”
【发布时间】:2016-07-09 19:02:46
【问题描述】:

远未完成,但现在我正试图让这个程序询问文件名并将其存储在字符串中,然后转换为 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());
    }
}

【问题讨论】:

    标签: c++ file validation loops boolean


    【解决方案1】:

    您遇到了一个称为“阴影”的问题。

    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 函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-23
      • 2012-05-03
      • 1970-01-01
      • 1970-01-01
      • 2011-10-31
      • 2016-09-16
      相关资源
      最近更新 更多