简体   繁体   English

字符串连接在 C 中不起作用 (TDM-GCC-64)

[英]String Concatenation not working in C (TDM-GCC-64)

This is my code这是我的代码

#include <stdio.h>
#include <conio.h>
#include <string.h>
int main()
{
  char fn[20], ln[20], fulln[20];
  int i, j, k;
  printf("Enter your first name: ");
  scanf("%s",fn);
  printf("Enter your last name: ");
  scanf("%s",ln);
  for(i=0,k=0;fn[i]!='\0'; i++, k++)
  {
    fulln[k] = fn[i];
  }
  k++;
  for(j=0;ln[j]!='\0';j++,k++)
  {
    fulln[k] = ln[j];
  }
  fulln[k] = '\0';
  printf("Your full name is %s",fulln);
  return 0;
}

Cannot understand what is wrong with it.无法理解它有什么问题。 It doesn't show the full name.它不显示全名。 I am using TDM-GCC-64(latest version)我正在使用 TDM-GCC-64(最新版本)

Your code is basically doing a strcpy and strcat manually.您的代码基本上是手动执行strcpystrcat

  for(i=0,k=0;fn[i]!='\0'; i++, k++)
  {
    fulln[k] = fn[i];
  }
  k++;
  for(j=0;ln[j]!='\0';j++,k++)
  {
    fulln[k] = ln[j];
  }
  fulln[k] = '\0';

There were problems with your code:您的代码存在问题:

  • You should initialise all the char buffer, like this: char fn[20] = "", ln[20] = "", fulln[41] = "";你应该初始化所有的字符缓冲区,像这样: char fn[20] = "", ln[20] = "", fulln[41] = "";

  • Also, you should make sure fulln is big enough to contain both fn and ln .此外,您应该确保fulln足够大以包含fnln As an example, make it 41 as above, to accommodate a space in between.例如,将其设置为 41,以容纳其间的空间。

  • Also, this line k++;此外,这一行k++; should be changed fulln[k++] = ' ';应该改变fulln[k++] = ' '; - that adds the space in between. - 这增加了两者之间的空间。

Btw, as you already include string.h there is no reason why you should not use the standard library strcpy and strcat .顺便说一句,因为您已经包含string.h所以没有理由不使用标准库strcpystrcat That means these two lines can replace your whole section of code:这意味着这两行可以替换您的整个代码段:

strcpy(fulln, fn);
strcat(fulln, " ");
strcat(fulln, ln);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM