c语言输入两个字符串,合并成一个字符串输出
时间: 2023-05-30 10:04:50 浏览: 329
以下是一个示例代码:
```
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100], result[200];
printf("请输入第一个字符串:");
fgets(str1, 100, stdin);
printf("请输入第二个字符串:");
fgets(str2, 100, stdin);
str1[strcspn(str1, "\n")] = '\0'; // 去掉输入字符串最后的换行符
str2[strcspn(str2, "\n")] = '\0';
strcpy(result, str1); // 将第一个字符串复制到结果字符串中
strcat(result, str2); // 将第二个字符串接在结果字符串后面
printf("合并后的字符串为:%s", result);
return 0;
}
```
在这个代码中,我们使用了`fgets()`函数来输入字符串,因为它可以避免输入字符串超过指定长度的问题。然后使用`strcspn()`函数去掉输入字符串最后的换行符,以避免在后面的字符串操作中产生不必要的问题。最后使用`strcpy()`和`strcat()`函数将两个字符串合并到一个结果字符串中,并输出结果字符串。
相关问题
c语言将两个字符串合并成一个字符串
可以使用C语言中的字符串函数strcat()将两个字符串合并成一个字符串。strcat()函数的原型如下:
```c
char *strcat(char *dest, const char *src);
```
其中,dest是目标字符串指针,src是源字符串指针。该函数将源字符串src追加到目标字符串dest的末尾,返回指向目标字符串的指针。
示例代码如下:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "hello";
char str2[] = "world";
strcat(str1, str2);
printf("合并后的字符串:%s\n", str1);
return 0;
}
```
输出结果为:
```
合并后的字符串:helloworld
```
C语言将两个字符串合并成一个字符串
可以使用C语言中的字符串函数`strcat()`来合并两个字符串。`strcat()`函数可以将第二个字符串追加到第一个字符串的末尾。下面是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[100] = "Hello, ";
char str2[] = "world!";
strcat(str1, str2); // 将 str2 追加到 str1 的末尾
printf("合并后的字符串: %s", str1);
return 0;
}
```
输出结果为:`合并后的字符串: Hello, world!`。
需要注意的是,在使用`strcat()`函数时,第一个参数必须是一个指向字符串的指针,并且该指针指向的内存空间必须有足够的大小来存储两个字符串的内容。否则可能会导致程序崩溃或者产生未知的错误。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)