为什么有些字符在C++中无法编辑?

问题描述 投票:0回答:1

我正在尝试用 C++ 编写自己的

strcat
函数,但它有一些问题。
我的输入是两个字符
c
a
,我的函数将返回一个指向
c
a
连接的字符的字符指针。

例如,
输入:

'abc'
'xyz'

预期输出:
'xyzabc'

我的函数的输出:
'xyza@▲∩'

我的函数返回一些与我的输入不同的特殊字符。

我调试了我的函数并发现:

  • i=0
    时,
    destination[3]
    =
    source[0]
    =
    'a'
  • 但是当
    i=1
    ,
    destination[8]
    =
    source[1]
    =
    'b'
  • i=2
    ,
    destination[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;
}
c++ strcat
1个回答
0
投票

strlen
返回从指针到它遇到的第一个
\0
的长度。在这里,在循环期间,您将覆盖
destination
指针中的该字符,因此后续调用会将长度返回到内存中恰好保存该字符的某个随机点。

一个简单的解决方法是在开始修改字符串之前提取

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.