我刚开始使用 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;
}
最佳答案
问题
- >
strncpy(目标、源、max_len)
strncpy 被定义为将最多 max_len
个字符从 source
复制到 destination
,包括 如果 source
在第一个 max_len
字节中不包含空字节,则为尾随的空字节。
在你的情况下,尾随的空字节将被包括在内,并且 destination
将在 “Over”
之后直接以 null 终止,这就是你看到的原因所描述的行为。
在调用 strncpy
后,myString
将因此比较等于:
"Over\0There"
解决方案
最直接的解决方案是不从 "Over"
复制尾随的空字节,这就像指定 4
而不是 一样简单5
到 strncpy
:
strncpy(myString, "Over", 4);
关于c++ - strncpy 函数不适合我正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22599766/