代码显示控制台上目录的内容,但它不等待`getch()`

时间:2017-03-06 10:57:53

标签: c++ windows dirent.h

当我使用第一批代码时没有错误,但是当我使用第二批代码时,程序运行并在控制台上显示目录的内容,但它不等待getch()和Windows说该程序已停止工作。

第一批代码(有效):

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

using namespace std;

int main() {

    DIR *dir=NULL;
    struct dirent *sdir;

    dir= opendir(".");

    while(sdir=readdir(dir)){

        cout<<endl<<sdir->d_name;
    }

    getch();
    return 0;
}

第二批代码(停止工作):

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

using namespace std;

int main() {

    DIR *dir=NULL;
    struct dirent *sdir;

    dir= opendir(".");
    sdir=readdir(dir); cout<<sdir->d_name;
    while(sdir){
        sdir=readdir(dir);
        cout<<endl<<sdir->d_name;
    }

    getch();
    return 0;
}

0 个答案:

没有答案