gpt4 book ai didi

c++ - 为什么这会进入无限循环?

转载 作者:太空宇宙 更新时间:2023-11-04 14:42:48 24 4
gpt4 key购买 nike

好的,所以我正在尝试创建一个包含文件夹、子文件夹及其文件的列表,但现在它不打印任何内容,而且似乎进入了无限循环。知道为什么吗?

 //infinate loop start
for(int j = 0; j < (int) dirs[i].folders.size(); j++){
dirs.push_back(Directory(dirs[i].folders[j]));

getfiles(dirs[i].dir,dirs[i].files);
getfolders(dirs[i].dir,dirs[i].folders);
}
//infinate loop end

这是完整的来源:

#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <errno.h>
#include <vector>
#include <string>
#include <iostream>

using namespace std;

struct Directory{
public:
int indent;
vector<string> files;
vector<string> folders;
string dir;
Directory(string mydir){ dir = mydir;}
};

int getfolders (string dir, vector<string> &folders)
{
DIR *dp;
struct stat st;
struct dirent *dirp;
if((dp = opendir(dir.c_str())) == NULL) {
cout << "Error(" << errno << ") opening " << dir << endl;
return errno;
}

while ((dirp = readdir(dp)) != NULL) {
stat(dirp->d_name, &st);

if(S_ISDIR(st.st_mode)){
if(dirp->d_name[0] != '.')
folders.push_back(string(dirp->d_name));
}
}
closedir(dp);
return 0;
}

/*function... might want it in some class?*/
int getfiles (string dir, vector<string> &files)
{

DIR *dp;
struct stat st;
struct dirent *dirp;
if((dp = opendir(dir.c_str())) == NULL) {
cout << "Error(" << errno << ") opening " << dir << endl;
return errno;
}

while ((dirp = readdir(dp)) != NULL) {
stat(dirp->d_name, &st);

if(!S_ISDIR(st.st_mode)){
files.push_back(string(dirp->d_name));
}
}
closedir(dp);
return 0;
}

int main()
{
struct Directory root = Directory(".");


vector<string> display = vector<string>();

cout << "hello\n";

getfiles(root.dir,root.files);
getfolders(root.dir,root.folders);

cout << "hello\n";

vector<Directory> dirs = vector<Directory>();

for(int i = 0; i < (int) root.folders.size(); i++){
dirs.push_back(Directory(root.folders[i]));

getfiles(dirs[i].dir,dirs[i].files);
getfolders(dirs[i].dir,dirs[i].folders);


//infinate loop start
for(int j = 0; j < (int) dirs[i].folders.size(); j++){
dirs.push_back(Directory(dirs[i].folders[j]));

getfiles(dirs[i].dir,dirs[i].files);
getfolders(dirs[i].dir,dirs[i].folders);
}
//infinate loop end
}

cout << "hello\n";

for (int i = 0; i < (int) root.folders.size();i++) {
cout << root.folders[i] << endl;
for(int j = 0; j < (int) dirs[i].folders.size(); j++){
cout << dirs[i].folders[j] << endl;
}
}
return 0;
}

最佳答案

for (int i = 0; i < (int) root.folders.size();i++) {
cout << root.folders[i] << endl;
for(int j = 0; j < (int) dirs[i].folders.size(); i++){
cout << dirs[i].folders[j] << endl;
}
}

我不太了解C++,但是第二个i++不应该是j++吗?否则 j 将始终为零,从而满足小于 dirs[i].folders.size() 的条件,因此循环永远不会结束。

关于c++ - 为什么这会进入无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3846980/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com