4
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
    char aa[35];
    int a;
    scanf("%d",&a);
    gets(aa);
    puts(aa);
}

It is not taking string from user but if I take the string before the integer value it is working fine.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
Sanchit Patiyal
  • 4,910
  • 1
  • 14
  • 31
  • What input are you trying to give your program? Try clearing the stream errors with [`clearerr`](http://en.cppreference.com/w/c/io/clearerr) if the `scanf` fails. – paddy Feb 15 '16 at 04:49
  • `gets` is probably reading the newline that was left after `scanf`. Also, never use `gets`, since there is no way to prevent buffer overflow. Use `fgets` instead. The man page for `gets` makes it clear that it should never be used. – Tom Karzes Feb 15 '16 at 05:10
  • Also note that any program with gets can be crashed or exploited by user input. In other words, never use gets. Use for example fgets. – hyde Feb 15 '16 at 05:52

4 Answers4

0

try placing another gets() :

gets(aa);
gets(aa);
JanLeeYu
  • 981
  • 2
  • 9
  • 24
0

Once scanf("%d",&a); takes numeric characters out of stdin to form the int for a, it is done. It does not consume a '\n' that may follow it.

gets(aa);, consumes data until '\n'.

So input like 1 2 3 x y Enter to the below will put 123 into a and "xy" into aa.

scanf("%d",&a);
gets(aa);

Input like 4 5 6 Enter to the above will put 456 into a and "" into aa.


Recommend using fgets() and add error handling.

if (fgets(aa, sizeof aa, stdin) == NULL) Handle_EOF();
if (sscanf(aa, "%d", &a) != 1) Handle_Nonnumeric_Input();

if (fgets(aa, sizeof aa, stdin) == NULL) Handle_EOF();
aa[strcspn(aa, "\n")] = '\0'; // truncate potential \n
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
0

For further information, u should search Google about buffered IO in this situation, because when you input a number first, you also have to pres "Enter", which means there are one "\n" character stays after a number is accepted So, before making input any string, remember to clear the buffered IO, there are 2 ways to do that Flush(stdin); or _flushall();

Always ask
  • 31
  • 4
-1

Use fflush in between scanf and gets to clear the buffer. It will work perfectly.

#include<stdio.h>
void main()
{
    char aa[20];     
    int b;
    scanf("%d",&b);
    fflush(stdin);
    gets(aa);
    puts(aa); 
    getchar();
}

Suggesting you not to use gets() since it does not validate the size of memory.