c - gets() 导致输出错误

标签 c gets

由于 gets() 导致输出错误...如图所示...程序在等待用户输入字符串之前打印 0。我需要读取“click 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 .

最佳答案

您的操作可能声明得太短。尝试一下

  char action[64];

相反。

然后替换

  gets(action); /// BAD CODE

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

您应该永远使用gets,它已经过时了

(使用fflush刷新输出缓冲区;memset正在清除action缓冲区;fgets code> 从 stdin 读取最多 63 个字节,因此您确定 action 将以空字节结束,就像每个 C 字符串应该的那样)

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

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

关于c - gets() 导致输出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32842386/

相关文章:

c - 关于GThread和文件复制的问题

c - 带控件的 DialogEx : Resizing?

c++ - Apple Mach-O 链接器错误,由于文件扩展名

c - AES_ctr128_encrypt() "Segmentation fault"(OpenSSL)

c - C 中的 gets() 字符串函数是否被认为是一种不好的做法?

c - gets() 不读取用户输入

c - 下标值既不是数组,也不是指针,也不是数组索引处的 vector

c - gets() 函数字符串行为

C - scanf() vs gets() vs fgets()

c++ - 输入一个未知数的整数流,并对其进行整数运算