gets()导致输出错误

时间:2015-09-29 11:10:37

标签: c gets

输出错误由于gets()...因为它可以在图像中看到...程序在等待用户输入字符串之前打印0。我需要阅读一串"点击X"格式,其中X是整数。在这种情况下有没有替代gets()?

 #include<stdio.h>
#include<stdlib.h>
int main()
{
    int n,k,i;
    char action[10];
    int *open;
    scanf("%d%d",&n,&k);                                    
    open= calloc( sizeof(int),n);               

    for(i=0;i<n;i++)
    {
        open[i]=0;
    }


    for(i=0;i<k;i++)
    {                                                     
        //gets to read an input  as "click 1"
      gets(action); 
      printf("%d\t%c",i,action[6]);     
    }
    free(open);                                                         
    return 0;
}

output of the above program....as it can be seen that instead of waiting for user to input string for action, it prints 0 .

2 个答案:

答案 0 :(得分:1)

你的action可能宣称太短了。尝试

  char action[64];

代替。

然后替换

  gets(action); /// BAD CODE

  fflush (NULL);
  memset (action, 0, sizeof(action));
  fgets  (action, sizeof(action), stdin);

从不使用gets,它已过时

(使用fflush刷新输出缓冲区; memset正在清除action缓冲区; fgetsstdin读取最多63个字节{1}},所以你确定action结尾将是一个空字节,因为每个C字符串都应该)

您应该让编译器向您提供所有警告和调试信息,例如如果使用GCC,请使用gcc -std=c99 -Wall -Wextra -g

您应该学习使用调试器(例如gdb

答案 1 :(得分:0)

&#39; scanf&#39;使用

fgets(action, sizeof(action), stdin);

消耗额外的换行符。作为&#39; scanf&#39;不能丢弃换行符,第一次迭代“得到”。拿新线。

不要使用&#39;使用&#39; fgets&#39;相反

您可以使用&#39; fgets()&#39;如

// Get the parameter of the parent, flow job - should be available as environment variable
def branch = build.environment.get("PARENT_PARAM_NAME")

parallel (
    // pass to child job
    { build("build1", CHILD_PARAM_NAME: branch)},
    // repeat as required
)