当前位置: 动力学知识库 > 问答 > 编程问答 >

c - Problems when using fgets and strcat

问题描述:

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

网友答案:

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.

网友答案:

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);
}
网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: