我不知道它是否相关,但我使用的是 Windows 7 和 Microsoft Visual Studio 2010。
我想做的就是向用户询问文件名,检查该名称的文件是否存在,如果存在,则向他们询问另一个
我的尝试
Main.cpp
std::cout << std::endl << "You must create a username" << std::endl;
std::cin >> username;
user.checkFile(username);
用户.cpp
void User::checkFile(std::string &username)
{
std::ifstream fin (username + ".txt");
while (fin.good)
{
std::cout << "This username already exists, please choose another.";
std::cin >> username;
if (fin.bad)
{
break;
fin.close();
}
}
}
这可以正确识别是否存在该名称的文件,但即使我键入不存在的名称,它仍然告诉我它确实存在
最佳答案
main.cpp
std::cout << std::endl << "You must create a username" << std::endl;
do
{
std::cin >> username;
if (user.checkFile(username))
break;
std::cout << "This username already exists, please choose another." << std::endl;
}
while (true);
用户.cpp
bool User::checkFile(const std::string &username)
{
FILE *fin = fopen((username + ".txt").c_str(), "r");
if (fin)
{
fclose(fin);
return false;
}
return true;
}
关于C++检查文件是否存在,如果存在,改变输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20504952/