0

I've written this code as a part of a bigger program :

   main()
{     int num;
      char word[50];
      list_head=NULL;


while(1)
      {     
            puts("Give number  : ");
            scanf("%d",num);
            if (num==0) break;
            printf("Give name : ");
            gets(word);
            if (strcmp(word,"")==0) break;
            add_node_to_list(num,word);
            }

and i when i run the program,the message "Give number : " appears on the screen and when i give a number then a message appears ("The program does not respond and will close") just like what happens in case of infinite loop.I deduced using debugging that the problem is scanf but i'm not sure.

4 Answers4

1

Two things.

  1. The & in scanf() as others mentioned:

    scanf("%d",&num);
    
  2. After taking the integer, there is a \n leftover in the input buffer. So gets() will input "".

    So do a getchar() after the scanf(). This would take away the \n from the input buffer and the gets() will work properly.

Also, it's better not to use gets for string input.

Community
  • 1
  • 1
HelloWorld123456789
  • 5,299
  • 3
  • 23
  • 33
0

scanf(3) needs variable's address to work properly.

Change

scanf("%d",num);

to

scanf("%d", &num);
chrk
  • 4,037
  • 2
  • 39
  • 47
0

You should provide address of the num, not the num itself. Now the application is trying to write to address 0 on first run.

Correct way would be

scanf("%d",&num);

Btw, you would know that if you have readed your compiler warnings.

Tomas Pastircak
  • 2,867
  • 16
  • 28
0

What the others said - the & in scanf("%d", &num) is important. Also, your scanf will read the number, but not the newline after it, so your gets() reads that newline and yield an empty string. Putting a blank behind the %d fixes that - scanf("%d ", &num).

Normally, you shouldn't gets() at all because it doesn't check for buffer overflows (funny things will happen if you enter more than 50 characters), but that's ok for now as you're still learning.

Guntram Blohm
  • 9,667
  • 2
  • 24
  • 31
  • I disagree on the `gets()`-issue. You shouldn't even get into the habit of using unsafe, deprecated functions. `gets()` is one of the worst of them. – EOF Apr 13 '14 at 13:24
  • what should i use insted of gets? –  Apr 13 '14 at 13:37
  • @chuckbartowski: use `char *fgets(char *s, int size, FILE *stream)` with your buffer being `char *s`, `int size` being the size of the buffer, and (in this case) `FILE *stream` being `stdin`. – EOF Apr 13 '14 at 15:17