如何在已经处理完毕后检查cin?

问题描述:

如果在检查另一个标准之前需要处理某些内容,检查输入的最佳方法是什么? 代码片段:如何在已经处理完毕后检查cin?

#include <string> 
#include <iostream> 
#include <dirent.h> 

bool has_suffix(const std::string &str, const std::string &suffix); 

void get_path_get_exit(std::string &path_input); 


int main() 
{ 
    DIR *dir; 
    struct dirent *ent; 
    std::string path_input; 
    std::getline(std::cin, path_input); 



    const char *path = path_input.c_str(); 
    dir = opendir(path); 
check: 
    while ((dir) == NULL && !path_input.empty()){ 
     /* could not open directory */ 

     std::cout << "Whoops, that didn't work. Please enter a valid directory path." << std::endl << "-->"; 
     std::getline(std::cin, path_input); 

     path = path_input.c_str(); 
     closedir(dir); 
     dir = opendir(path); 
    } 
    if ((dir) != NULL) { 

     unsigned int counter = 0; 

     while ((ent = readdir (dir)) != NULL) { 
      counter++; 
     } 
    /*check if the folder is empty*/ 
     if (counter == 0){ 
     /*how to surpass the goto statement?*/ 
      goto check; 
     } 
     std::string files[counter]; 


     closedir(dir); 
     dir = opendir(path); 
     counter = 0; 
     while ((ent = readdir (dir)) != NULL) { 

       files[counter] = ent->d_name; 
       std::cout << "[" << counter+1 << "] " << files[counter] << std::endl; 
       counter++; 

     } 
     closedir(dir); 
    } 
} 

正如你所看到的,我想检查CIN输入,并在接下来的if语句我想要检查,如果打开的目录是空的。有没有更好的方法可以跳到最上面的'检查'的开头,以便再次进入while循环,并再次用上面的条件检查新的输入? Goto确实有效,但使用它我感到有点惭愧。

+0

不应该是'!path_input.empty()'在while条件吗? –

+0

当然,对不起,我错了。我纠正了它! – Dominik

提取物检查条件的功能。这是好的程序员在这种情况下所做的。

bool IsDirectoryValidForThisOperation(DIR *dir, std::string& failDesdcription) 
{ 
    if (!dir) { 
     failDesdcription = "Invalid directory"; 
     return false; 
    } 
    if (readdir(dir)) == NULL) { 
     failDesdcription = "Directory is empty"; 
     return false; 
    } 
    // TODO: restore state of dir 

    return true; 
} 

一个好的代码总是spited成小功能,因为:

  • 更容易阅读
  • 许多地方FO代码可以在另一种情况下
  • 更容易被重用写测试
  • 它更容易调试
  • 代码将自我记录
+0

谢谢。我会仔细看看它! – Dominik

+0

得到它的工作,只需要将上面的while循环添加到bool函数,因为dirent.h也可以识别。和..作为文件。所以我必须检查后缀。 – Dominik

我可能没有完全理解你的问题,但我听起来像你需要一个do..while循环

const char *path = path_input.c_str(); 
    dir = opendir(path); 
    do 
    { 
     while (//some criteria that aren't met){ 
      /* could not open directory */ 

      std::cout << "Whoops, that didn't work. Please enter a valid directory path." << std::endl << "-->"; 
      std::getline(std::cin, path_input); 

      path = path_input.c_str(); 
      closedir(dir); 
      dir = opendir(path); 
     } 
     if ((dir) != NULL) { 

      unsigned int counter = 0; 

      while ((ent = readdir (dir)) != NULL) { 
       counter++; 
      } 
    /*check if the folder is empty*/ 
    } while(counter == 0) 
+0

谢谢,但我认为你误会了我。我的问题是,如何在进行第一次检查之前跳到,以便新的输入也由上面的要求验证。 – Dominik