1

I am having a problem with my C code. See the code below:

#include<stdio.h>

int main()
{
    char name[30]; // Declaring the string-array
    FILE* fileptr; // Declaring the FILE pointer
    char file[10];
    printf("Please enter the file name : ");
    scanf("%s",file);//Taking a single word input
    fileptr = fopen(file,"w");
    if (fileptr == NULL)
    {
        printf("No such file found !");

    }
    puts("Please enter some strings here: ");
    gets(name);  //Line 17
    fputs(name,fileptr);
    printf("\nStrings saved to %s",file);
    fclose(fileptr);

}

The problem is in Line 17 I used gets() instead of scanf() but I don't know if it's right or not. I can't get any user input here using gets() or other functions. But I want to have multiple word or line string input and the skips after printing the line 16 & then it prints line 19. It doesn't gives me any chance for the input. What should I do? Please help me out. Thanks in advance. :)

  • 2
    [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 Jun 08 '21 at 00:49
  • *"I can't get any user input"*. Can you please clarify what that means exactly? Give the exact input, expected behaviour and actual behaviour. – kaylum Jun 08 '21 at 00:50
  • What should I use then to take multiple line user input? –  Jun 08 '21 at 00:51
  • 2
    Never use `gets()` — it isn't safe. Add a loop to get more than one line of input. Note that `gets()` removes newlines and `fputs))` doesn't add them. – Jonathan Leffler Jun 08 '21 at 00:51
  • 4
    Note that `scanf()` left a newline in the input which `gets()` immediately read and discarded and returned an empty string. – Jonathan Leffler Jun 08 '21 at 00:57
  • @Rafi Research `fgets()`. – chux - Reinstate Monica Jun 08 '21 at 01:37

2 Answers2

0

Add a function called remove_trash like this

void remove_trash(void)
{
    char trash[81];
    fgets(trash, 80, stdin);
}

Call it before doing gets(name) //Line 17.

Dharman
  • 30,962
  • 25
  • 85
  • 135
ADBeveridge
  • 650
  • 3
  • 15
0

You would use scanf to read formatted input, but needs to be used carefully not to cause a buffer overflow. To safely read strings you would need to use fgets, to read from the stdin defining a threshold.

As specified on the manpage:

char *fgets(char *restrict s, int size, FILE *restrict stream);

// fgets() reads in at most one less than size characters from stream
// and stores them into the buffer pointed to by s. Reading stops after
// an EOF or a newline. If a newline is read, it is stored into the buffer.
// A terminating null byte ('\0') is stored after the last character in the
// buffer. 
Danillo Souza
  • 81
  • 1
  • 8
  • I used `fgets()` but it was not working either. I used `scanf()`but wanted more control on the string input. –  Jun 09 '21 at 02:54