我刚刚开始使用C ++,所以我在这里可能会有一个愚蠢的错误。下面是我的代码以及评论中的输出。我正在使用Xcode。
#include <iostream>
#include <string.h>
using namespace std;
int main() {
char myString[] = "Hello There";
printf("%s\n", myString);
strncpy(myString, "Over", 5); // I want this to print out "Over There"
cout<< myString<<endl; // this prints out ONLY as "Over"
for (int i = 0; i <11; i++){
cout<< myString[i];
}// I wanted to see what's going on this prints out as Over? There
// the ? is upside down, it got added in
cout<< endl;
return 0;
}
答案 0 :(得分:1)
问题
strncpy (destination, source, max_len)
strncpy 定义为最多从max_len
复制source
个字符到destination
,包括尾随空字节source
在第一个max_len
字节内不包含空字节。
在你的情况下,尾随的空字节将包括在内,并且destination
将在"Over"
之后直接以空值终止,这就是你看到所描述的行为的原因。
因此,您对strncpy
myString
的致电比较等于:
"Over\0There"
解决方案
最直接的解决方案是不复制"Over"
的尾随空字节,这就像指定4
而不是5
到strncpy
一样简单:
strncpy(myString, "Over", 4);
答案 1 :(得分:1)
strncopy的文档如下:
char * strncpy ( char * destination, const char * source, size_t num );
将源的前几个num字符复制到目标。如果结束 源C字符串(由空字符表示)是 在复制num个字符之前找到,目的地被填充 用零写,直到写入总数为num个字符。
通过调用strncpy(myString, "Over", 5)
,您实际上正在复制&#34; Over \ n&#34;进入myString。最好用strlen(source)作为最后一个参数调用strncpy。
答案 2 :(得分:1)
尝试以下
#include <iostream>
#include <string.h>
using namespace std;
int main() {
char myString[] = "Hello There";
printf("%s\n", myString);
strncpy(myString, "Over", 4); // I want this to print out "Over There"
strcpy( myString + 4, myString + 5 );
cout<< myString<<endl; // this prints out ONLY as "Over"
for (int i = 0; i <10; i++){
cout<< myString[i];
}// I wanted to see what's going on this prints out as Over? There
// the ? is upside down, it got added in
cout<< endl;
return 0;
}