簡體   English   中英

使用 fgets() 接收句子輸入

[英]Using fgets() to recieve a sentence input

我似乎對某些代碼有問題。 該代碼的目的是將一個短語轉換為豬拉丁語。

似乎這段代碼不會接受用戶輸入,在我們說 if (x == 1) 的塊中。 它會做的是它會自動將 NULL 作為 fgets 的輸入,我不知道為什么。

我已經在這個問題上花費了太多時間,如果您就如何改進此代碼提出任何建議,我將不勝感激。 請就我將來如何改進我的問題發表評論。

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

int pigLatin()
{
    char phrase[250] = { 0 };
    char pigPhrase[300] = { 0 };
    char * tokens[300] = { 0 };
    char fileName[260] = { 0 };

    FILE * read = NULL;
    FILE * write = NULL;

    int i = 0;
    int x;
    int size;

    while (i < 10000) {
        i++;
        x = 0;
        printf("Enter one(1) to input via console, two(2) to input via .txt, or (3) to exit:\n");
        scanf_s("%d", &x);
        if (x == 1) {
            printf_s("Enter your Phrase Do not include:\nany punctuation, words less than 2 letters long, or words seperated by blanks:");

            fgets(phrase, sizeof phrase, stdin);

            phrase[strlen(phrase) - 1] = '\0';

            printf_s("\nPhrase Entered:%s\n", phrase);
            system("pause");
        }
        else if (x == 2)
        {
            printf("Enter name of input file:\n");
            scanf_s("%s", fileName, 260);
            printf("File name:\n%s\n", fileName);
            if (fopen_s(&write, fileName, "r") == 0)
            {
                scanf_s("%s", phrase, 260);

            }
        }
        else if (x == 3)
        {
            break;
        }
        else
        {
            printf("Invalid Statement\n");
            break;
        }
    }

    return 0;
}

scanf("%d", &number); 將讀取一個整數,但將其他所有內容保留在流中,包括輸入數字后按 [Enter] 生成的'\\n' 這個留在流中的換行符隨后被fgets()消耗,而沒有給你輸入的機會。

使用scanf()后清除流:

int clear(FILE *stream)
{
    int ch;  // reads until EOF or a newline is encountered:
    while((ch = fgetc(stream)) != EOF && ch != '\n');
}

// ...
int number;
if(scanf("%d", &number) != 1) {
    // handle error;
}

clear(stdin);

char foo[42];
fgets(foo, sizeof(foo), stdin);

// ...

暫無
暫無

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

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