-2

error in output due to gets()...as it can be seen in the image ... program prints 0 before waiting for user to enter the string. I need to read a string of "click X" format where X is a integer. Is there any alternative to gets() to use in this situation?

 #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 .

smasher
  • 294
  • 2
  • 17

2 Answers2

1

Your action is probably declared too short. Try

  char action[64];

instead.

Then replace

  gets(action); /// BAD CODE

with

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

You should never use gets, it is obsolete.

(use fflush to flush output buffer; the memset is clearing the action buffer; the fgets is reading at most 63 bytes in it from stdin, so you are sure action is ending will a null byte as every C string should)

You should ask your compiler to give you all warnings and debug info, e.g. use gcc -std=c99 -Wall -Wextra -g if using GCC.

You should learn to use the debugger (e.g. gdb)

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
0

After 'scanf' use

getchar();

to consume extra newline. As 'scanf' can not discard newline, first iteration of 'gets' take the newline.

Don't use 'gets', use 'fgets' instead

You can use 'fgets()' as

fgets(action, sizeof(action), stdin);
ashiquzzaman33
  • 5,781
  • 5
  • 31
  • 42