簡體   English   中英

C代碼在第一次循環時缺少getchar()命令

[英]C code missing getchar() command in while loop first time round

我正在用C語言編寫一個菜單系統,代碼可以正常工作,但是由於某種原因,第一次為菜單第一次輸入while循環時,它會跳過getchar()命令並再次運行while循環,但是第二次是作品? 關於為什么這樣做的任何想法?

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "structs.h"

int main(void) 
{
    FILE *fp = NULL;
    char fileName[25], line[200], userInput = ' ';
    int len;

    while (fp == NULL) 
    {
        printf("Enter The File To Load In: \n");
        scanf("%s", fileName); // Ask User For File Name
        fp = fopen(fileName, "r"); // Open File To Read
        if (fp == NULL) 
        {
            perror("Error While Loading File\n");
        }
    }

    while (userInput != 'g') 
    {   
        printf("        |User System|\n");
        printf("A) Save Current Data To A File\n");
        printf("B) Enter Details\n");
        printf("C) View Details\n");
        printf("D) Amend Details\n");
        printf("E) Search by Award Title\n");
        printf("F) Search by Surname\n");
        printf("G) Shut Down\n");
        userInput = getchar();

        if (userInput == 'c') 
        {
            fgets(line, 200, fp);
            len = strlen(line);
            printf("%s", line);
            userInput = getchar();
        }
    }
} 

在“ scanf”使用之后

getchar();

消耗額外的換行符。 由於“ scanf”不能舍棄換行符,因此“ getchar();”的第一次迭代 換行。

因此,您將getchar()放置在scanf之后,以消耗額外的換行符('\\ n')

scanf("%s", fileName);
getchar();

最好使用“ fgets”而不是scanf因為文件名可能有空間。 您可以使用'fgets()'作為

fgets(fileName, sizeof(fileName), stdin);
fileName[strlen(fileName)-1] = 0; //Replace newline with '\0' character

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM