2
#include <stdio.h> 

main()
{
    int t,i;
    scanf("%d",&t);

    check();
    return 0;
}

int check()
{ 
    char s[20];
    gets(s);

    printf("%s",s);
    return 1;
}

When I run this check function, this function does not take input and immediately exits. I don't know why please tell me

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
kartik chauhan
  • 151
  • 2
  • 16
  • Never ever use `scanf` without checking its return value. – Gerhardh Oct 18 '19 at 11:15
  • Please see [Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers?](https://meta.stackoverflow.com/questions/326569/under-what-circumstances-may-i-add-urgent-or-other-similar-phrases-to-my-quest) and [How to ask](https://stackoverflow.com/help/how-to-ask). – S.S. Anne Oct 18 '19 at 11:24

2 Answers2

1

Use a space character following the %d in scanf to read in the whitepace that follows the value entered.

In other words, use:

scanf("%d ", &t);

Also note that gets has been deprecated for years. It is vulnerable to buffer overrun attacks. Use fgets instead.

Here is a fixed version of this program:

#include <stdio.h> 

#define CHECK_BUFSIZE 19

int check()
{ 
    char s[CHECK_BUFSIZE+1];
    fgets(s, CHECK_BUFSIZE, stdin);
    printf("%s",s);
}

int main()
{
    int t,i;
    scanf("%d ",&t);   
    check();
    return(0);
}
S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
suspectus
  • 16,548
  • 8
  • 49
  • 57
  • Your `CHECK_BUFSIZE` in combination with the `fgets` is wrong. Instead, you can/should use `char s[20]; fgets(s, sizeof(s), stdin); printf("%s",s);` optionally having `20` be the value of a macro. – S.S. Anne Oct 18 '19 at 12:10
0

Declaration of the function is must if you write it after main function. gets has been deprecated so, scanf is a better variant .

#include <stdio.h> 
int check();
main()
{
    int t,i;
    scanf("%d",&t);

    check();
    return 0;
}

int check()
{ 
    char s[20];
    scanf("%s",s);

    printf("%s",s);
    return 1;
}

Also if you want string input with spaces in it then use "%[^\n]" instead of using "%s" in the scanf function

  • "gets has been deprecated so, scanf is a better variant ." To the best of my knowledge, scanf with %s is no better than gets. – L. F. Oct 18 '19 at 13:02
  • i mentioned it in the answer earlier, if one needs to add space in a string then use scanf with "%[^\n]" ,that might be better then gets function . – Neet Gabani Oct 18 '19 at 13:13
  • 2
    gets is deprecated because it has overflow problems. scanf with %s has the same problem, so it is not a better variant. See [What can I use for input conversion instead of scanf?](https://stackoverflow.com/q/58403537). – L. F. Oct 18 '19 at 13:18