远没有完成,但现在我试图让这个程序要求文件名并将其存储在字符串然后转换为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 回答
您遇到了一个名为“阴影”的问题 .
上面的代码将永远运行,因为在while循环的上下文中的
i
是在main中声明的i
.您的代码执行此操作:
您可能需要考虑重构代码以避免重复并简化它:
我把它作为练习留给你重新介绍你的isValid函数 .