2014-10-17 71 views
0

这是我的主要功能..为什么我的第二个“scanf”被跳过?

printf("How many marking components in the course? "); 
    scanf("%d", &numberOfComponents); 
    for (int i=0; i<numberOfComponents; i++){ 

      char c[MAX_STR]; 
      printf("enter next component name: "); 
      fgets(c, sizeof(c), stdin); 
      scanf(c, " %c", &c); 


      Component comp; 

      initComp(&comp, c); 
      class.comps[i] = comp; 

      } 

    printf("How many marking schemes? "); 
    scanf(" %d", &numberOfSchemes); 

我已经试过白色的空间,但它仍然存在

+5

什么是'scanf(c,“%c”,&c);'应该是什么意思?你用这个'scanf'调用你想要做什么? – AnT 2014-10-17 01:07:28

回答

0

混合fgets()scanf()经常造成问题。

scanf("%d"...留下任何下面的空格,如'\n'stdinfgets()得到。 scanf(c, " %c", &c);(这可能意味着是scanf(" %c", c);sscanf(c, " %c", c);)后会发生同样的情况。

scanf("%d", &numberOfComponents); 
... 
fgets(c, sizeof(c), stdin); 

推荐使用仅fgets()获取用户输入并使用sscanf()strtol()等来解析该输入。

fgets(c, sizeof(c), stdin); 
sscanf(c, "%d", &numberOfComponents); 

.... 

fgets(c, sizeof(c), stdin); 
// I do not think you need the following line of code. 
// Besides it is UB as it attempts to scan and save into the same buffer. 
// sscanf(c, "%c", &c); 

fgets(), sscanf()省略结果的错误检查,但还是好做的。

+0

通过“下面的代码行”你的意思是f得到了吗?或者scanf? – Bauer 2014-10-17 01:40:58

+0

@Nolan Hodge'sscanf(c,“%c”,&c);' – chux 2014-10-17 03:21:49

1

您应该测试您的输入操作是否有效;当你不这样做时,事情就会变得不合时宜。

这次调用scanf()

scanf(c, " %c", c); 

应该(在chux诊断他answer)进行不同的写的,但我认为它应该更像:

char filler; 
if (scanf(" %c", &filler) != 1) 
    …report problem… 

原来的版本使用只读作为格式字符串的行,几乎肯定会失败匹配第二个输入。如果您只使用scanf(" %c", c)这是最简单的编辑,那么用下一个非空字符覆盖输入行的第一个字符。

这就是为什么您要让用户在组件名称后输入额外数据的问题。他们必须输入一些东西。在下一个fgets()上,代码将在第一个字符之后读到下一个换行符。所以,如果你键入:

component-1 
component-2 

第一fgets()会读component-1和换行;修改后的scanf()会将component-2c读为c[0],然后接下来的fgets()将在下一次迭代中将omponent-2加上换行符加上c

你可以看到更多的是怎么回事的加入代码来打印你读,你读它:

printf("Line 1: [[%s]]\n", c); // after the fgets() 
printf("Line 2: [[%s]]\n", c); // after the scanf() 

这是最基本的调试技术之一;回应你读过的内容,以确保程序获得了你认为它的数据。