使用char数组的strcat函数
strcat function using char arrays
以下代码的目的是仅使用基本数组操作创建一个strcat函数。用户输入目标char数组,并将源字符阵列附加到其末尾。除了它在某些输入char阵列中吐出的随机字符外,我的代码最有效。例如,如果我将目的地输入为奶酪,而我的来源输入为汉堡,则输出是芝士汉堡。但是,如果我的目的地输入是龙,而我的来源输入是飞,则蜻蜓应该是输出。但是,输出作为蜻蜓@。我不知道怎么了,需要帮助。
#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] != ' '; i++)
{
if ( destination[i] != ' ')
{
x = x + 1;
}
}
for(int i=0; source[i] != ' '; i++)
{
destination[i + x] = source[i];
}
cout << destination << endl;
}
基本上,您只需要在destination
数组的末尾添加一个null-character( ' '
)。
这是正确的(稍微简化)实现:
void mystrcat(char destination[], const char source[])
{
int x = 0;
while (destination[x] != ' ')
{
x++;
}
for (int i=0; source[i] != ' '; i++)
{
destination[x++] = source[i];
}
destination[x] = ' ';
}
,但您应该知道您对destination
数组的大小没有安全性征象...
您不会终止目标字符串。您需要在末尾添加' '
字符。
简短代码:
void _mystrcat_(
__in char * out,
__in char * in)
{
while (*out) out++;
do { *out++ = *in++; } while (*in);
*out = 0x0;
}
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 类似于strcat()的函数出现问题
- 字符串函数:strcat()
- 从 'char' 到 'char*' strcat 函数的转换无效
- 使用指针编写 strcat 函数
- 使用char数组的strcat函数
- 我正在尝试创建自己的 strcat() 函数,而不是使用库实现函数<cstring>
- 为什么我无法将迭代器作为字符串传递给函数 strcat() 的参数
- 如何修复strcat函数中的错误
- C++ 字符串行为在定义和在 strcat 函数中是不同的