gpt4 book ai didi

c++ - 要求一个输入文件,直到它在 C++ 中是正确的

转载 作者:搜寻专家 更新时间:2023-10-31 01:09:50 24 4
gpt4 key购买 nike

我正在尝试用 C++ 读取一个文件。我向用户询问文件名,如果文件存在我打开它但如果它不存在我一直询问直到输入有效的文件名。但是,当用户首先输入错误的文件时,即使输入了有效的文件名,我的程序也会将其识别为错误。这是我的代码:

ifstream input;
string filename;
cout<<"Enter the file name";
cin>>filename;
input.open(filename.c_str());
while(input.fail())
{
cout<<"Incorrect filename, please enter again";
cin>>filename;
input.open(filename.c_str());
}

有人可以帮忙吗?谢谢

最佳答案

输入错误需要清空输入。试试这个:

 ifstream input;
string filename;
cout<<"Enter the file name";
cin>>filename;
input.open(filename.c_str());
while(input.fail())
{
input.clear();
cout<<"Incorrect filename, please enter again";
cin>>filename;
input.open(filename.c_str());
}

关于c++ - 要求一个输入文件,直到它在 C++ 中是正确的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16586259/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com