gets() 和 getchar() 被忽略

gets() and getchar() are being ignored

我是新来的,会用c编码,所以请耐心等待我。

我的问题是使用 getchar() 和 scanf(" %c") 进行递归调用获取字符输入。

编译器忽略 getchar(),并输出 '\n' 而不是等待字符。

发布行:pfile->content.folder.files[i] = newFile(getchar());

阻止我创建 sub-files/folders... 函数 newFile 应该创建一个文件夹或文件(一个文本文件),如果它是一个文件夹,我应该 提供文件夹内的文件数量,并递归调用在已创建的文件夹内创建文件。

typedef struct {
    char *name;                 //name of File
    char type;                  // 'f' - data file, 'd'-folder.
    union {
        char data[81];             //f -80 chars array for content of file.
        struct {                //d -arry of pointers to 'File' Files.
            struct File ** files;
            unsigned int size;
        }folder;
    }content;
}File;

函数:

FILE * newFile(char type){
    File *pfile = (File*)malloc(sizeof(File)); //creating new File
    if (type != 'f' && type != 'd') { // in case of wrong input of type.
        printf("Wrong input!\n");
        return NULL;
    }
    //File *pfile = (File*)malloc(sizeof(File)); //creating new File
    printf("Enter File name: ");
    scanf(" %s", &pfile->name);// Name of new File

    if (type == 'f') {      // New File is 'folder'
        printf("Enter number of files in folder '%s': ",&pfile->name);
        scanf(" %d", &pfile->content.folder.size);
        if (pfile->content.folder.size == 0) { // Zero files in the folder
            pfile->content.folder.files[pfile->content.folder.size - 1] = NULL; // No more files / empty folder
        }
        pfile->content.folder.files = (File**)malloc(pfile->content.folder.size * sizeof(File));

        for (int i = 0; i < pfile->content.folder.size; ++i) { // creates 'size' file per folder
            printf("Enter type of %d file(d-folder,f-file): ", i + 1);
            pfile->content.folder.files[i] = newFile(getchar());  //<<<<<=====ISSUE HERE !
        }
        return pfile;

    }
    else /*if (type == 'd')*/ { //File creation
        printf("Enter file's text:\n");
        scanf(" %s",&pfile->content.data);
    }
    return pfile;   
}

如果有任何想法或改进建议,我将不胜感激。

段.

scanf 的调用在输入缓冲区中留下一个换行符。使用 %d%sscanf 的其他调用在读取时会跳过 whitespace。 getchar 但是读取缓冲区中的下一个字符恰好是换行符。

而是使用 scanf 和格式字符串 " %c"%c 格式说明符不会跳过白色 space,但领先的 space 会。

char newtype;
scanf(" %c", &newtype);
pfile->content.folder.files[i] = newFile(newtype);