【问题标题】:Why is my code not outputting a string when I scan an integer before it, but outputting the string when I scan the integer after?为什么我的代码在扫描之前的整数时不输出字符串,但在扫描之后的整数时输出字符串?
【发布时间】:2020-10-03 21:39:39
【问题描述】:

这是一个非常基本的 scanf/printf 问题,但由于某种原因,我在试图让我的程序正确读取和打印字符串时遇到了困难。如果我跑:

#include <stdio.h>

int main(void) {
   int    userInt;
   double userDouble;
   char userChar = 'z';
   char userString[8];
   // FIXME: Define char and string variables similarly
   
   
   printf("Enter integer:\n");
   scanf("%d", &userInt);
   printf("Enter character:\n");
   scanf("%c", &userChar);
   printf("Enter string:\n");
   scanf("%s", userString);
   
   
   printf("%d %c %s", userInt, userChar, userString); 
      
   return 0;

使用这些输入

23 a howdy

我得到以下输出:

Enter integer:
Enter character:
Enter string:
23   a

如果我运行以下命令:

#include <stdio.h>

int main(void) {
   int    userInt;
   double userDouble;
   char userChar = 'z';
   char userString[8];
   // FIXME: Define char and string variables similarly
   
   
   
   printf("Enter character:\n");
   scanf("%c", &userChar);
   printf("Enter string:\n");
   scanf("%s", userString);
   printf("Enter integer:\n");
   scanf("%d", &userInt);
   
   
   printf("%d %c %s", userInt, userChar, userString); 

return 0;

使用以下输入运行:

a howdy 23

我得到了这个输出,这是我一直期待的。

Enter character:
Enter string:
Enter integer:
23 a howdy

我的问题是我必须在字符和字符串之前扫描整数以查找我正在处理的问题,我无法弄清楚为什么第二种方法有效而第一种方法无效。任何建议将不胜感激。

【问题讨论】:

  • 当你说“使用以下输入运行”时,你是如何给它这些输入的?
  • 通过 zybooks。我只是在“输入程序输入”的框中分别输入了 23 和 23。
  • scanf("%d", &amp;userInt); 仅消耗来自输入的23。之后的所有内容仍在stdin 中,包括紧跟在23 之后的空间。所以下一个scanf("%c", &amp;userChar); 读取空间然后scanf("%s", userString); 读取a
  • 这很有意义。谢谢。

标签: c


【解决方案1】:

scanf 通常会丢弃前导空格,但不会丢弃 %c,因为那样您将无法读取空格字符。

匹配一系列宽度计数字符(默认为 1); next 指针必须是指向 char 的指针,并且必须有足够的空间容纳所有字符(不添加终止 NUL)。 通常会跳过前导空格。要先跳过空格,请在格式中使用显式空格。

要遍历此...您输入23 a howdy。让我们看看每个调用时输入流上的内容。

// "23 a howdy"
scanf("%d", &userInt); // reads 23

// " a howdy"
scanf("%c", &userChar); // reads a single character, a space.

// "a howdy"
scanf("%s", userString); // reads up to the next whitespace, 'a'

// " howdy" remains on input.

如果我们用引号将它们打印出来以查看空格...

// 23 ' ' 'a'
printf("%d '%c' '%s'\n", userInt, userChar, userString);

要让%c 跳过空格,请在其前面放置一个空格。

scanf(" %c", &userChar);

scanf is full of these sorts of pitfalls,您永远无法确定输入缓冲区中还剩下什么。因此,将读取与扫描分开会更安全。使用fgets 读取一个换行符并使用sscanf 进行解析。

【讨论】:

  • 您始终可以确定输入缓冲区中还剩下什么——您只需要小心并了解各种转换的细微差别和限制。
  • 在 scanf 中您无法真正处理的一种情况是整数溢出,无论如何这都很棘手。
猜你喜欢
  • 1970-01-01
  • 2021-11-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-24
相关资源
最近更新 更多