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

时间:2017-10-09 15:30:20

标签: c++ validation input 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语句中尝试检查,如果打开的目录为空。是否有更好的方式来跳过&#34;跳#34;到顶部的开头&#39;检查&#39;为了再次进入while循环并再次使用上限标准检查新输入? Goto确实有用,但我觉得使用它有点惭愧。

2 个答案:

答案 0 :(得分:0)

我可能不完全理解你的问题,但我觉得你需要一个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)

答案 1 :(得分:0)

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

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

一个好的代码总是吐成小函数,因为:

  • 更容易阅读
  • 代码的许多部分可以在另一个上下文中重用
  • 编写测试更容易
  • 更容易调试
  • 代码将自我记录