c - 使用 C 并尝试创建一个疯狂的库。

标签 c

正如我的职位所说,我是一名学习 C 的新程序员。这是我第二天的编程,我需要帮助解决我代码中的这个问题。我正在制作一个疯狂的库,虽然没有出现错误,但第一个 scanf 占用 2 行而不是其他所有 scanf 使用的 1 行。

代码如下:

#include <stdio.h>

int main()
{
    char verb[20];
    char loc[20];
    char noun1[20];
    char noun2[20];
    char adj[20];

/* The following is the part where you input words. It sets them as strings (named word1-5, as stated above)*/

    printf("Welcome to Mad Libs! \nAnswers can only be one word long. \nPlease enter a verb.\n");
    scanf("%s\n",verb);

    printf("Now enter a location!\n");
    scanf("%s\n",loc);

    printf("Now enter a noun!\n");
    scanf("%s\n",noun1);

    printf("Now enter another noun!\n");
    scanf("%s\n",noun2);

    printf("Now please enter an adjective!\n");
    scanf("%s\n",adj);

/* It all comes together here. The code is supposed to take the strings set previously and put them into this story. */
/* The dashes and various /n's are there to make the final Mad Lib easier to read */    

    printf("\n\nHere is your Mad Lib:\n------------------------------ \nHolly %s down to the %s.\nOnce she got there she bought some %s and ate it!\nAfterwards, Holly brought it home and let her %s eat it.\nHolly is a %s girl!\n------------------------------ \n",verb,loc,noun1,noun2,adj);
return 0;
}

它是在 Ubuntu 上结合使用 Vi 和 Sublime Text 2 制作的。

就像我说的,我在编译时没有收到任何错误,而且一切似乎都井井有条,问题是一旦我在终端中运行它,我必须输入第一个答案(对“Welcome to Mad Libs”的回答! 答案只能是一个词长。请输入一个动词。”) 两次,它需要两个。

如果您对我的意思感到困惑,请尝试自己运行它(它应该可以在 OS X 和 Linux 中作为 .c 文件运行),老实说,我不知道如何很好地描述错误。它让我输入第一个答案两次,并在显示最终的疯狂库时导致问题。

最佳答案

只需使用scanf("%s", ...),而不是scanf("%s\n")\n 直到后来才到达那里。 (哦,顺便说一下,这也是一种防止缓冲区溢出的好方法,因此您可以考虑使用 fgets 等)

它现在的工作方式是:

  1. 您键入一行并按 Enterscanf 获取线路,但没有 \n,所以它仍在等待。
  2. 您键入下一行并按 Enterscanf 现在在上一行的末尾有 \n 并使用该字符串。第一行已读取,第二行现在在缓冲区中,scanf 正在等待另一个已存在的 \n
  3. 转到 2

这具有将所有答案移动一个的效果。

关于c - 使用 C 并尝试创建一个疯狂的库。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14391701/

相关文章:

c - 如何开始?使用 C 的简单文本编辑器

c - 为什么我应该使用归约而不是原子变量?

找不到/lib64/ld-linux-x86-64.so.2

C - 没有循环的位操作

c - fprintf 不写任何东西

c - scanf 没有响应?

c - getch() 和 getchar() 有什么区别?

c - 在 Mac OSX 上接收电源通知(尤其是关机)

c - 有效 PE 文件上的 STATUS_INVALID_IMAGE_HASH (0xc0000428)

c - 如何正确实现 float 乘法(软件FP)