我正在尝试从C数组中复制一个特定的单词并将其放入另一个c数组中,以便稍后可以显示输出,但是当我执行该程序时,第一个函数调用起作用了((输出/终端) “复制\“光亮\”,应显示\“光亮\”。\ n“; 但是,当我再次调用该函数时,它给我的结果(输出/端子)是超级的,而不是超级的(因为我在参数中指定了,我想复制前五个字符)。怎么了?
#include <iostream>
#include <cstring>
#include <cctype>
#include <stdio.h>
#include <string.h>
#include <algorithm>
using std::cin;
using std::cout;
using std::endl;
// function declarations
char* copy(char* destination, const char* source, size_t num);
int main()
{
const int WORDSIZE = 15;
char words[][WORDSIZE] = {"sprightful", "reason to row", "New York", "Bolton", "Frida", ""};
char word[WORDSIZE];
copy(word, words[0], sizeof(word) - 1);
cout << word << endl << endl;
copy(word, "Supercalifragilisticexpialidocious", 5);
cout << word << endl << endl;
return 0;
}
char* copy(char* destination, const char* source, size_t num)
{
strncpy(destination, source, num);
return destination;
}
答案 0 :(得分:1)
您不会在两个函数调用之间清除word
。在第二次通话中,它只会覆盖前5个字符(“超级”),其余的是您上一次通话的结果。
答案 1 :(得分:0)
@Brandon是正确的。尝试在函数调用之间清除单词:
int main()
{
const int WORDSIZE = 15;
char words[][WORDSIZE] = { "sprightful", "reason to row", "New York", "Bolton", "Frida", "" };
char word[WORDSIZE];
// Test the copy function
std::cout << "Copy \"sprightful\", should see \"sprightful\".\n";
copy(word, words[0], sizeof(word) - 1);
cout << word << endl << endl;
memset(&word[0], 0, sizeof(word)); //Clear the char array.
// Test the limit on the copy function
cout << "Copy \"Supercalifragilisticexpialidocious\", should see \"Super\".\n";
copy(word, "Supercalifragilisticexpialidocious", 5);
cout << word << endl << endl;
getchar();
return 0;
}