[英]What's wrong here? I'm not getting my string concatenated?
I have written this code from an algorithm given by my friend.我用我朋友给出的算法编写了这段代码。 But when I try to implement it it's not working.
但是当我尝试实现它时它不起作用。 Can anyone tell me error here?
谁能在这里告诉我错误?
#include<stdio.h>
void scat(char [], char []);
int i,j;
void main()
{
char s1[10],s2[10];
printf("Enter first string: ");
scanf("%s",&s1);
printf("Enter second string: ");
scanf("%s",&s2);
scat(s1,s2);
}
void scat(char s1[], char s2[])
{
char str1[10],str2[10],str3[20];
for(i=0;str1[i]!=NULL;i++)
str3[i]=str1[i];
for(j=0;str2[j]!=NULL;j++,i++)
str1[i]=str3[j];
printf("\nConcanated string is %s",str3);
}
#include<stdio.h>
void scat(char [], char[]);
int main()
{
char s1[10], s2[10];
printf("Enter first string: ");
scanf("%s", s1);
printf("Enter second string: ");
scanf("%s", s2);
scat(s1, s2);
return 0;
}
void scat(char s1[], char s2[])
{
char str3[20];
int i,j;
for (i = 0; s1[i] != '\0'; i++)
str3[i] = s1[i];
for (j = 0; s2[j] != '\0'; j++, i++)
str3[i] = s2[j];
str3[i] = '\0';
printf("\nConcanated string is %s", str3);
}
U used undeclared variables in function. U 在 function 中使用了未声明的变量。 Also I fix some mistakes you made.
我也修正了你犯的一些错误。
What are you copying?你在复制什么? str1 into str3 and str3 into s1.
str1 进入 str3 和 str3 进入 s1。 What does it mean?.
这是什么意思?。 Even str1, str2 have nothing useful in them.
甚至 str1、str2 也没有任何用处。 Just unknown character so copying them is undefined.
只是未知字符,因此复制它们是未定义的。 Try this.
尝试这个。
void scat(char *s1, char *s2)
{
char str3[20];
for(i=0;s1[i]!='\0';i++){
str3[i]=s1[i];}
for(j=0;s2[j]!='\0';j++,i++)
str3[i]=s2[j];
str3[i]= '\0'; // This is must
printf("\nConcatenated string is %s",str3);
}
for c, strings are simply a pointer to char arrays, so they can't really be concatenated.对于 c,字符串只是指向 char arrays 的指针,因此它们不能真正连接起来。 but we can combine them in another way.
但我们可以用另一种方式组合它们。 we can use strcat from the string.h library.
我们可以使用 string.h 库中的 strcat。 this works:
这有效:
#include <stdio.h>
#include <string.h>
#define MAX_LIMIT 200
int main() { char str1[200], str2[200];
printf("Enter the first string: ");
fgets(str1, MAX_LIMIT, stdin);
printf("Enter the second string: ");
fgets(str2, MAX_LIMIT, stdin);
strcat(str1, str2);
printf("\nConcanated string is %s", str1);
return 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.