【发布时间】: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的主要原因之一。