c - 使用 fgets() 接收句子输入

标签 c string input

我似乎遇到了一些代码问题。该代码的目的是获取一个短语并将其转换为 pig latin。

在我们说 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);

// ...

关于c - 使用 fgets() 接收句子输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52939521/

相关文章:

c - C 中的指针优先级和取消引用

python - 在 Python 中使用数学特殊字符

java - Android,自定义适配器,字符串和长ID

javascript - 如何在javascript函数中使用输入框的值

jquery - 从输入 [type=color] 更新显示颜色

c - YouCompleteMe 仅建议 "local"使用的代码

c++ - Sublime Text 启动单独的命令窗口(C/C++)

c - 段错误(核心已转储)- 错误在哪里?

string - 从字符串中获取整数月份值

java - gwt 列的通用输入单元(在创建列构造函数之前更改单元格类型或了解属性的单元格类型)