连接(添加)两个字符串

时间:2015-11-27 05:53:28

标签: c char concatenation fgets

我被告知编写一个包含连接函数的程序。该程序应使用fgets (&s1[0], len1+1, stdin)收集输入字符串 然后将两者相加以生成最终产品。

我的问题在于程序会编译,但它不会在屏幕上显示任何内容,这就是我所拥有的。如果没有这种方法,我无法理解如何解决问题。

//function to terminate the program incase reach of 0
int str_len (char s[])
{          
int i=0;
while (s[i]= NULL)
++i;
return i+1;
}
char string_cat (char*s1, char*s2)
{
//ADDING THE TWO STRINGS
int str_len(char s[])
char *s1 [80]= {'\0'};
char *s2 [40]= {'\0'};
int len1=str_len(s1);
int  len2=str_len(s2);
if (int x=0; len1+len2<80; \0;
return;
}
int main ()
{
char string_cat(char*s1,char*s2)
int str_len(char s[])
//RECIVING THE STRINGS TO ADD
char s1 [80];
char s2 [40];
int i=0;
for (i; i !=0; ++i)
{
printf("What is the first sentence?: ")
fgets(*s1[0], 75+1, stdin);
printf("What is the second sentence?:")
fgets(*s2[0],35+1,stdin);
string_cat(*s1,*s2);
printf("The two sentences added together produce the following: %c",s1 )
}
++i
return 0;
}

3 个答案:

答案 0 :(得分:1)

除了其他人指出的for循环的错误之外,str_len函数中的while循环是错误的。 你应该使用while(s [i]!= NULL)而不是s [i] = null。一个等号,“=”,是作业;两个等号,“==”,是比较;和感叹号等于,“!=”,表示不相等。

其次,将s1和s2重新分配给string_cat函数中的不同内存位置,其第一个字符为NULL,“\ 0”。如果按照上面的指示更正你的str_len函数,这将始终给你的str_len一个长度为0,如果没有根据在运行时占用你的内存的内容纠正一个随机数的长度。

第三[仍然在string_cat函数中],你的 if(int x = 0; len1 + len2&lt; 80; \ 0; 没有意义。你没有做任何连接在这个功能中。

很抱歉没有为您提供解决方案,因为这是一个简单的练习。如果我要为你提供代码,我觉得要破坏你。

答案 1 :(得分:0)

在您的代码中有很多编译错误。复制粘贴已编译的代码。

检查此行代码

int i=0;
for (i; i !=0; ++i)

因此,你没有得到任何东西。在for循环中,条件i !=0总是失败,因此它不会进入循环内。

答案 2 :(得分:0)

第一个问题在这里

int i=0;
for (i; i !=0; ++i)

您将值0设置为变量i,然后检查它是否不等于0.由于i等于0,所以此检查无法通过。

第二个问题也是循环。我根本无法得到你需要循环的原因,因为根本没有使用i,所以放弃了增量。因此,就我而言,根本不需要循环。