【问题标题】:Using fgets() to recieve a sentence input使用 fgets() 接收句子输入
【发布时间】:2018-10-23 00:37:40
【问题描述】:

我的某些代码似乎有问题。代码的目的是获取一个短语并将其转换为猪拉丁语。

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

【问题讨论】:

  • 为什么在 c++ 中使用 fgets?
  • @DYZ 我认为很明显它是 C 错误地标记为 C++。
  • 是的,对不起,我的坏人。
  • @Urist_mcDwarf - 获取用户输入的最重要方面是检查用于确定成功或失败的任何函数的返回。然后您进一步检查任何范围值(如果需要),最后考虑输入缓冲区中剩余的任何字符(请参阅下面的 Swordfish 答案)。 scanf 留在输入缓冲区中的内容是新 C 程序员遇到 scanf 问题的主要原因,也是建议所有用户输入使用 fgets 的主要原因之一。

标签: c string input


【解决方案1】:

scanf("%d", &amp;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);

// ...

【讨论】:

  • 流到底是什么?我知道它与文件有关,而且我知道标准输入是一种流。 EOF 也是正确的关键字吗?另外,您希望使用 if 语句从我的程序中看到什么样的错误?
猜你喜欢
  • 2021-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-24
  • 1970-01-01
相关资源
最近更新 更多