【问题标题】:strcat function using char arrays使用 char 数组的 strcat 函数
【发布时间】:2014-03-08 16:46:18
【问题描述】:

以下代码的目的是创建一个仅使用基本数组操作的 strcat 函数。目标字符数组由用户输入,源字符数组附加到它的末尾。除了它为某些输入字符数组吐出的随机字符外,我的代码大部分都可以正常工作。例如,如果我的目标输入是奶酪,源输入是汉堡,那么输出应该是芝士汉堡。但是,如果我的目标输入是龙而我的源输入是苍蝇,那么蜻蜓应该是输出。但是,输出为dragonfly@。我不知道出了什么问题,需要帮助。

#include <iostream>
#include <string>

using namespace std;

void mystrcat ( char destination[], const char source[]);

int main(){
    char source[80];
    char destination[80];
    cout << "Enter a word: ";
    cin >> source;
    cout << "\n";
    cout << "Enter a second word: ";
    cin >> destination;

    mystrcat(destination, source);

}
void mystrcat ( char destination[], const char source[]){

    int x=0;
    for(int i=0; destination[i] != '\0'; i++)
    {
        if ( destination[i] != '\0')
        {
            x = x + 1;
        }
    }
    for(int i=0; source[i] != '\0'; i++)
    { 
        destination[i + x] = source[i];
    }
    cout << destination << endl;
}

【问题讨论】:

  • 你需要null终止结果。
  • 丢失索引,只使用指针。在此过程中,正确构造的附加循环将包括终止符。 See it live.

标签: c++ arrays string function strcat


【解决方案1】:

基本上,您只需在 destination 数组的末尾添加一个空字符 ('\0')。

这是正确的(并且稍微简化了)实现:

void mystrcat(char destination[], const char source[])
{
    int x = 0;
    while (destination[x] != '\0')
    {
        x++;
    }
    for (int i=0; source[i] != '\0'; i++)
    { 
        destination[x++] = source[i];
    }
    destination[x] = '\0';
}

但您应该注意,您对 destination 数组的大小没有安全断言...

【讨论】:

    【解决方案2】:

    您不会终止目标字符串。您需要在末尾添加'\0' 字符。

    【讨论】:

      【解决方案3】:

      短代码:

      void _mystrcat_(
      __in char * out,
      __in char * in)
      {
          while (*out) out++;
          do { *out++ = *in++; } while (*in);
         *out = 0x0;
      }
      

      【讨论】:

      • 请解释一下你的代码sn-p。只需添加几句话来解释解决方案。这将使您的答案质量更高。
      猜你喜欢
      • 1970-01-01
      • 2019-09-19
      • 1970-01-01
      • 2014-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-04
      • 1970-01-01
      相关资源
      最近更新 更多