这是我的代码。我希望它询问文件名,直到它是一个有效名称。我将如何做?在我当前的代码中,它在失败后停止。
void X() {
string fileName;
ifstream inFile;
cout << "Enter the name of the file: " << endl;
cin >> fileName;
ifstream input;
input.open(fileName);
if (input.fail()) {
cout << "Could not open the file " << fileName << endl;
}
}
最佳答案
void X()
{
string fileName;
ifstream inFile;
do {
cout << "Enter the name of the file: " << endl;
cin >> fileName;
ifstream input;
input.open(fileName);
if(input.fail())
{
cout<< "Could not open the file "<< fileName<< endl;
}
}
while(input.fail())
}
应该可以解决问题。这样,只要文件打开操作不成功,代码就会继续尝试。
关于c++ - 如何在这里创建一个循环? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14913662/