如果在检查另一个条件之前需要处理某些内容,检查输入的最佳方法是什么? 代码片段:
#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/