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

时间:2013-05-16 11:30:01

标签: c++ iostream

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

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());
}

有人可以帮忙吗?感谢

1 个答案:

答案 0 :(得分:4)

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

 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());
}