0

I have to write a program using the scanf and the gets methods, I tried with this code:

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


int main() {
    char string[50];

    printf("first string (printf and scanf):\t");
    scanf("%s", &string);
    printf("%s", string);

    printf("\n\nsecond string (gets and puts):\t");
    gets(string);
    puts(string);
}

But gets() is receiving a \n as input, how can I fix it? I've already tried with a getchar() before this, but I don't know if it's correct.

cipryyyy
  • 39
  • 1
  • 8
  • 4
    Also: Never use `gets`. It is dangerous. Use `fgets` instead. [Why is the gets function so dangerous that it should not be used?](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) – kaylum Feb 27 '21 at 21:06
  • 1
    If you're calling `scanf`, your best bet is *not* to follow it with `fgets` (or with `gets`, which has its own problems). They do not mix well. The hoops you have to jump through to get the functions to "play well together" are not satisfying and not worth it. – Steve Summit Feb 27 '21 at 21:15
  • the `gets()` function has been depreciated for years and completely eliminated by C11 – user3629249 Feb 27 '21 at 22:48
  • regarding: ` scanf("%s", &string);` The 'bare' `%s` has no limit on the number of characters that can be input. This means the user can overflow the input buffer, resulting in undefined behavior. To avoid this problem, use a MAX Characters modifier that is 1 less than the length of the input buffer. One less because this 'input conversion' specifier always appends a NUL byte to the input – user3629249 Feb 27 '21 at 22:53
  • regarding: `scanf("%s", &string);` This function stops inputting when it encounters any `white space`, including the '\n' So when this function is done, the user entered '\n' is still in the input stream, Therefore the first char read by the next input statement will be '\n'. the '\n' can be easily consumed via a call to `getchar()` so your doing the right thing – user3629249 Feb 27 '21 at 23:00
  • @SteveSummit I've swapped them and it works, thank you – cipryyyy Mar 01 '21 at 19:55
  • @user3629249 it's a school project so I have to use `gets`, thanks for the information anyway – cipryyyy Mar 01 '21 at 19:57
  • @cipryyyy Sorry to make a big deal out of this, but in 2021, if you have an instructor who is requiring you to use `gets` and forbidding alternatives, that instructor is guilty of some pretty serious malpractice. (You're welcome to tell him/her we said so.) – Steve Summit Mar 01 '21 at 20:03

0 Answers0