0

I have written a simple program in C which is as follows:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
int length;
printf("Enter the length of the string:\t");
scanf("%d",&length);
char str1[10];
printf("Enter string:\t");
gets(str1);
printf("%s",str1);
return 0;
}

When I execute it - I get an output as:

Enter the length of the string: 5
Enter string:
Process returned 0 (0x0)   execution time : 1.740 s
Press any key to continue.

I don't know why it doesn't ask for the string input and simply quits the program.

2 Answers2

0

When you enter 5 and press enter which is "\n" then "\n" remains in stream and gets assigned to str1. You need to take that "\n" out of the input stream for which many choices are there. You can figure that out. :) Perhaps later I will edit this answer to let you know.

Edit 1:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    int length;
    char c;
    printf("Enter the length of the string:\t");
    scanf("%d%c",&length, &c);

    char str1[10];
    printf("Enter string:\t");
    gets(str1);
    printf("%s",str1);
    return 0;
}

This is incorrect way of doing it but your code will at least start working. You can also simply call getc(stdin) which is slightly better. The scanf regex specified in the other answers where it has been marked as duplicate will also work but is ugly and unnecessarily complicated.

I have not tested this and it may not work.

Shiv
  • 1,912
  • 1
  • 15
  • 21
0

When you type '5’ followed by the enter key, you are sending two chars to the program - '5' and newline. So your first scanf gets the '5' and the second gets the newline, which it converts to the number zero.

See How to read a line from the console in C?

Community
  • 1
  • 1
slim
  • 40,215
  • 13
  • 94
  • 127