Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在这里创建循环?C++;_C++_Loops - Fatal编程技术网

C++ 如何在这里创建循环?C++;

C++ 如何在这里创建循环?C++;,c++,loops,C++,Loops,这是我的密码。我想让它要求文件名,直到它是一个有效的名称。我该怎么做?在我当前的代码中,它在失败后停止 void X() { string fileName; ifstream inFile; cout << "Enter the name of the file: " << endl; cin >> fileName; ifstream input; input.open(fileName); if

这是我的密码。我想让它要求文件名,直到它是一个有效的名称。我该怎么做?在我当前的代码中,它在失败后停止

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(){
字符串文件名;
河流充填;
cout文件名;
ifstream输入;
打开(文件名);
if(input.fail()){
cout
void X()
{
字符串文件名;
河流充填;
做{
cout文件名;
ifstream输入;
打开(文件名);
if(input.fail())
{

你的意思是
而(!input.fail())
?哎呀,错过了。谢谢!循环条件现在没有意义了。它可能应该被反转,这样循环才能执行,直到用户输入一个可以打开的文件名。你的第一个版本可能是正确的。是的。我反应太快了。现在已经晚了。@David:It is
while(input.fail())
因为我们希望循环在文件打开后立即退出,所以只有在
open
调用失败时才循环。@Nordin:如果我的答案是您要找的,您能接受吗?最后一个大括号不在代码块中,您需要将它缩进4个空格。
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())
}