c++ - 已经处理后如何检查cin?

标签 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 语句中尝试检查打开的目录是否为空。有没有更好的方法“跳”到顶部“检查”的开头,以便再次进入 while 循环并再次使用更高的标准检查新输入? Goto 确实有用,但我觉得用它有点惭愧。

最佳答案

提取一个检查条件的函数。这就是优秀的程序员在这种情况下所做的。

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

一个好的代码总是被恶意分解成小函数,因为:

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

关于c++ - 已经处理后如何检查cin?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46650034/

相关文章:

Java连续输入代码

c++ - 在真实 3D 环境(例如建筑物)中寻路

c++ - 结构作为 unordered_map 的键

php - ZF2 空输入过滤器和数字验证器

javascript - 如何提醒动态添加的输入框的重复值?

jquery - 获取密码字段的掩码值?

c++ - 在没有 USES_CONVERSTION 的情况下从 const char * 转换为 LPTSTR

c++ - 来自整数和无效操作数的小数 *更新

javascript - Chrome 无法进行 jquery 表单验证

php - 当我将表单提交到服务器时,如何检查表单中是否存在输入字段?