#include <iostream> using namespace std; char* mystrcat(char *s1, char* s2); int main() { char s1[80]; char s2[40]; cin >> s1 >> s2; mystrcat(s1, s2); cout << s1 << endl; return 0; } char* mystrcat(char *s1, char* s2) { /********* Begin *********/ /********* End *********/ }补全该代码,使得输入两个字符串A和B后,程序会返回连接后的字符串,并且在A和B之间加上一个字符“-”。例如:输入:Com puter 预期输出:Com-puter
时间: 2023-07-01 14:28:34 浏览: 47
```c++
#include <iostream>
using namespace std;
char* mystrcat(char *s1, char* s2);
int main() {
char s1[80];
char s2[40];
cin >> s1 >> s2;
mystrcat(s1, s2);
cout << s1 << endl;
return 0;
}
char* mystrcat(char *s1, char* s2) {
/********* Begin *********/
char* p = s1;
while(*p != '\0') {
p++;
}
*p = '-';
p++;
while(*s2 != '\0') {
*p = *s2;
p++;
s2++;
}
*p = '\0';
return s1;
/********* End *********/
}
```
相关问题
#include<iostream> using namespace std; int main() { char s1[]="Goodbye",s2[8]; char*from=s1,*to=S2; while(* from) { *to++=*from++; } to='\0'; cout<<s1; cout<<s2; return 0; }检查程序错误
在程序中,存在以下错误:
1. `using namespace std;` 应该在 `#include<iostream>` 前面。
2. `char*from=s1,*to=S2;` 中的 `S2` 应该改为 `s2`。
3. `to='\0';` 应该改为 `*to='\0';`。
修改后的程序如下:
```
#include <iostream>
using namespace std;
int main()
{
char s1[] = "Goodbye", s2[8];
char* from = s1, * to = s2;
while (*from)
{
*to++ = *from++;
}
*to = '\0';
cout << s1 << endl;
cout << s2 << endl;
return 0;
}
```
#include <iostream> #include <cstring> using namespace std; char *ReplaceString(char *str, char *s1, char *s2); int main() { char str[100], s1[10], s2[10]; cin >> str >> s1 >> s2; char *result = ReplaceString(str, s1, s2); cout << result << endl; return 0 ; } char *ReplaceString(char *str, char *s1, char *s2) { /********* Begin *********/ char *a,*b,*c; a=str; b=s1; c=s2; while(*str) { strtok(a,b); strcpy(b,c); } /********* End *********/ }这段代码怎么修改
这段代码存在一些问题,需要进行修改:
1. 在函数`ReplaceString`中,需要将替换后的字符串返回给主函数,因此需要定义一个新的字符数组,用于存储替换后的字符串,并在函数末尾将其返回。
2. 在`while`循环中,需要将`strtok`的返回值赋给`a`,否则`a`的值不会发生改变,导致替换失败。
3. 使用`strcpy`函数替换字符串时,需要先将目标字符串的长度扩展至源字符串的长度,否则会导致内存访问错误。
修改后的代码如下:
```
#include <iostream>
#include <cstring>
using namespace std;
char *ReplaceString(char *str, char *s1, char *s2);
int main() {
char str[100], s1[10], s2[10];
cin >> str >> s1 >> s2;
char *result = ReplaceString(str, s1, s2);
cout << result << endl;
delete[] result; // 释放内存
return 0;
}
char *ReplaceString(char *str, char *s1, char *s2) {
char *new_str = new char[strlen(str) + 1]; // 新建字符数组,用于存储替换后的字符串
char *a = new_str, *b = s1, *c = s2; // a指向新字符数组的起始位置
while (*str) {
char *p = strtok(str, b);
if (p != NULL) {
strcpy(a, p);
a += strlen(p);
strcpy(a, c);
a += strlen(c);
str += strlen(p) + strlen(b);
}
else {
strcpy(a, str);
break;
}
}
return new_str;
}
```