|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 冷回清风暖 于 2020-7-17 20:59 编辑
在编写代码过程中 发现- while(*++strDes != '\0');
复制代码 能正常连接字符串。
- while(*strDes++ != '\0');//优先级 ++ > *
复制代码 把该部分代码替换成这样的,运行代码不能成功连接字符串。
调试了下也不知道为什么
附上strcat代码
- char *strcat1(char *strDes, const char *strSrc)
- {
- char *address = strDes;
- if(strDes == NULL || strSrc == NULL)
- return NULL;
- while(*++strDes != '\0');//优先级 ++ > * ,*strDes++失败??
- while((*strDes++ = *strSrc++) != '\0');
-
- return address;
- }
复制代码
附上完整代码
- #include<stdio.h>
- #include<Windows.h>
- #include<stdlib.h>
- char *s_gets(char *st, int n);
- char *strcat1(char *strDes, const char *strSrc);
- int main(void)
- {
- char strdes[100]= {0};
- char strsrc[100] = {0};
- char *result;
- printf("请输入被连接的字符串:");
- if((result = s_gets(strdes,100)) == NULL)
- exit(EXIT_FAILURE);
- printf("请输入要连接的字符串:");
- if((result = s_gets(strsrc,100)) == NULL)
- exit(EXIT_FAILURE);
- strcat1(strdes,strsrc);
- printf("连接结果为:%s",strdes);
- system("pause");
- return 0;
- }
- char *s_gets(char *st, int n)
- {
- char *ret_val;
- int i = 0;
- ret_val = fgets(st,n,stdin);
- while(st[i] != '\n' && st[i] != '\0')
- i++;
- if(st[i] == '\n')
- st[i] = '\0';
- else while(getchar() != '\0')
- continue;
- return ret_val;
- }
- char *strcat1(char *strDes, const char *strSrc)
- {
- char *address = strDes;
- if(strDes == NULL || strSrc == NULL)
- return NULL;
- while(*++strDes != '\0');//优先级 ++ > * ,*strDes++失败??
- while((*strDes++ = *strSrc++) != '\0');
-
- return address;
- }
复制代码
- while(*++strDes != '\0');
复制代码
是先自加,然后再进行判断,判断的是当前的字符,也就是说当前到了字符串的结尾字符'\0'就跳出循环,拼接的时候,覆盖了原字符串的末尾字符'\0',所以能正确拼接。
- while(*strDes++ != '\0');//优先级 ++ > *
复制代码
这种写法是先判断,然后再进行自加,判断的是自加前的字符,也就是说跳出循环的时候,当前字符不是'\0',而是'\0'的下一个单元,拼接之后,原字符串末尾的'\0'并没有被覆盖掉,所以看上去没有完成拼接。
|
|