正在回答
7回答
请同学新建一个回答贴出来代码,你写在回复中,又包含注释,不便于帮助调试~
Tender10
2018-05-07 10:17:15
#include <iostream> #include <assert.h> #include <string> using namespace std; char *str_cat(char *des,const char *src) { assert((des != NULL) && (src != NULL)); char *address = des; while (*des != '\0') des++; while ((*des++ = *src++)!= '\0') ; return address; } char *str_copy(char *des,const char *src) { assert((des != NULL) && (src != NULL)); char *address = des; while ((*des++ = *src++)!= '\0') ; return address; } int str_len(const char *a){ assert(a!=NULL); int add = 0; while(*a++ != '\0'){ add++; } return add; } int main(){ char a[] = {"I am a chinese"}; char b[] = {"I love china"}; char ds[20]={"I am a chinese"}; if(str_len(a) >= str_len(b)){ cout<<str_copy(ds,a)<<endl; cout<<str_cat(ds,b)<<endl; }else{ cout<<str_copy(ds,b)<<endl; cout<<str_cat(ds,a)<<endl; } return 0; }
修改一下你的代码,如上所示,如果还有什么不明白的地方,可以在问答里继续提问。
MasonM
2018-05-03 21:19:17
#include<iostream> #include<string> #include<assert.h> using namespace std; char *str_copy(char *a, const char *b) { assert((a != NULL) && (b != NULL)); char *add = a; while ((*a++ = *b++) != '\0'); return add; } char *str_cat(char *a, const char *b) { assert((a != NULL) && (b != NULL)); char *add = a; while (*a != '\0')a++; *a = ' '; a++; while ((*a++ = *b++) != '\0'); return add; } int str_len(const char *a) { assert(a != NULL); int add = 0; while (*a++ != '\0') { add++; } return add; } int main() { //定义两个字符串 char a[] = { "I am chinese" }; char b[] = { "I love china" }; char ab[30]; //比较两个字符串的长度,根据结果连接字符串,并输出连接后的字符串 if (str_len(a) >= str_len(b)) { cout << str_copy(ab, a); cout << str_cat(a, b); } else { cout << str_copy(ab, b); cout << str_cat(b, a); } system("pause"); return 0; }
按照这样编码,字符可以正常显示,但会弹窗这样报错,这是为什么呢,请老师解答一下,谢谢老师!
MasonM
2018-05-03 16:51:17
#include<iostream> #include<string> #include<assert.h> using namespace std; char *str_copy(char *a, const char *b) { assert((a != NULL) && (b != NULL)); char *add = a; while ((*a++ = *b++) != '\0'); return add; } char *str_cat(char *a, const char *b) { assert((a != NULL) && (b != NULL)); char *add = a; while (*a != '\0')a++; while ((*a++ = *b++) != '\0'); return add; } int str_len(const char *a) { assert(a != NULL); int add = 0; while (*a++ != '\0') { add++; } return add; } int main() { //定义两个字符串 char a[] = { "I am chinese" }; char b[] = { "I love china" }; char ab[30]; //比较两个字符串的长度,根据结果连接字符串,并输出连接后的字符串 if (str_len(a) >= str_len(b)) { cout << str_copy(ab, a); cout << str_cat(a, b); } else { cout << str_copy(ab, b); cout << str_cat(b, a); } system("pause"); return 0; }
老师代码这样写还是会报错呢,而且输出变成I am chineseI am chineseI love china的,该怎么办?谢谢老师!
C++零基础入门 热门编程语言 二级考试必备
- 参与学习 529 人
- 提交作业 110 份
- 解答问题 594 个
无论您是零基础、还是想晋升,亦或是想转型,C++无疑都是最佳选择。本路径共分为基础语法、指针与引用、面向对象三大模块,为你开启入门C++编程的大门!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星