Kumar
Kumar

Reputation: 175

Compiler ignoring subsequent commands

I have the following C code:

#include <stdio.h>

int main()
{
    char* ptr;
    printf("Enter the word: ");
    gets(ptr);
    printf("The input string is: ");
    puts(ptr);
    return 0;
}

It compiles and asks for the input, but after I enter the input, it takes a pause and exits. No further commands are executed or displayed. I am unable to understand the problem. Please help.

Upvotes: 0

Views: 102

Answers (1)

Peaky_001
Peaky_001

Reputation: 1137

#include <stdio.h>

int main()
{
    char str[100] = "";
    printf("Enter the word: ");
    fgets(str, sizeof str, stdin);
    printf("The input string is: ");
    printf("%s", str);
    return 0;
}

Try to use fgets(). gets() is dangerous to use because gets() is inherently unsafe, because it copies all input from STDIN to the buffer without checking size. This allows the user to provide a string that is larger than the buffer size, resulting in an overflow condition.

puts is simpler than printf but be aware that the former automatically appends a newline. If that's not what you want, you can fputsyour string to stdout or use printf.

Upvotes: 2

Related Questions