1

I am having some problems while using fgets and strcat (I tried to replace the fgets into scanf and the program worked). It seems the strcat is not working.

char name[256];
char text[256];

fgets(name,250,stdin);
strcat(name,".txt");
printf("%s\n",name);

The output is (in separate lines):

d
.txt
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
  • 1
    You need to remove the new line from name after `fgets` – Ed Heal Mar 31 '16 at 20:56
  • Take a look at [my answer to another question](http://stackoverflow.com/a/36341266/434551). While the questions are different, the solution is exactly the same. – R Sahu Mar 31 '16 at 20:57
  • If `strcat` weren't working, you wouldn't see `.txt` in the output – M.M Mar 31 '16 at 21:00

3 Answers3

2

You have to remove the newline from the input. Like this:

fgets(name, 250, stdin);
char *p = strchr(name, '\n');
if (p)
    *p = '\0';
strcat(name, ".txt");

Obviously you'd want to add some error checking there but this demonstrates the idea.

Carey Gregory
  • 6,836
  • 2
  • 26
  • 47
1

because '\n' is also consumed in your fgets function, it will be displayed like that. You can use scanf instead for simplicity:

int main() {
   char name[256];
   char text[256];

   scanf("%250s",name);
   strcat(name,".txt");
   printf("%s\n",name);
}
Pooya
  • 6,083
  • 3
  • 23
  • 43
  • Note: `scanf("%s")` only reads until the next space, see http://stackoverflow.com/questions/1247989/how-do-you-allow-spaces-to-be-entered-using-scanf for details. – Roland Illig Mar 31 '16 at 21:23
  • @RolandIllig that is right, since the example shows something like a filename "d.txt" it is not viable to catch the space and it doesn't require extra functions to drop the final "\n" either. However if the code's intention is really for getting a hole string including space, tabs ,... then you are right – Pooya Mar 31 '16 at 21:26
1

Using the rarely-used function strcspn, this becomes simple and error-prone:

if (fgets(name, 250, stdin) != NULL) {
  strcpy(name + strcspn(name, "\n"), ".txt");
  ...
}

The strcspn function counts the number of characters that are not \n; the c in strcspn means complement. Therefore, no matter whether or not the name contains a newline or not, the .txt will always be added at the correct position.

Roland Illig
  • 40,703
  • 10
  • 88
  • 121