为什么有些字符不能在C++中编辑?

icnyk63a  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(99)

我正在尝试用C++编写自己的strcat函数,但它有一些问题。
我的输入是两个字符ca,我的函数将返回一个字符指针,指向ca连接的字符。
比如说,
输入:'abc''xyz'
预期输出:'xyzabc'
我的函数的输出:'xyza@▲∩'
我的函数返回一些与我的输入不同的特殊字符。
我调试了我的函数,发现:

  • i=0时,destination[3] = source[0] = 'a'
  • 但当i=1destination[8] = source[1] = 'b'时,
  • i=2destination[9] = source[2] = 'c'
  • destination[10] = '\0'
#include<iostream>
#include<string.h>
using namespace std;

char* mystrcat ( char * destination, const char *source){
    for (int i=0; i<strlen(source); i++) {
        destination[strlen(destination)+i] = source[i];
    }
    destination[strlen(destination)+strlen(source)]='\0';
    return destination;
}

int main() {
    char c[100];
    cin.getline(c, 99);
    char a[100];
    cin.getline(a,99);

    mystrcat(a,c);
    cout<<a;
    return 0;
}

字符串

0lvr5msh

0lvr5msh1#

strlen返回从指针到它遇到的第一个\0的长度。在这里,在循环期间,您在destination指针中覆盖了这个字符,因此随后对strlen的调用将返回内存中恰好保存这个字符的某个随机点的长度。
一个简单的解决方法是在开始修改字符串之前提取strlen结果:

char* mystrcat (char *destination, const char *source) {
    int destLen = strlen(destination);
    int srcLen = strlen(source);
    for (int i = 0; i < srcLen; i++) {
        destination[destLen + i] = source[i];
    }
    destination[destLen + srcLen] = '\0';
    return destination;
}

字符串

e4eetjau

e4eetjau2#

下面给出的是代码的正确实现。

#include<bits/stdc++.h>
using namespace std;
void mystrcat ( char* destination, const char *source){
    int p;
    for(p=0; destination[p] != '\0'; p++);//pointing to the index of the last 
    character of x

    for(int q=0; source[q] != '\0'; q++,p++)
    {
    destination[p]=source[q];
    }
    destination[p]='\0';
    }
int main() {
   char c[100];
   cin.getline(c, 99);
   char a[100];
   cin.getline(a,99);
   mystrcat(a,c);
   cout<<a;
   return 0;
 }

字符串
由于源代码的长度将在代码中得到更新,因此它会给出特殊的符号作为输出。

相关问题