[英]strncpy function not working for me correctly
我只是從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 (destination, source, max_len)
strncpy定義為最多將max_len
字符從source
復制到destination
,如果source
的前max_len
個字節中不包含空字節,則包括尾隨空字節。
在您的情況下,尾隨的空字節將包括在內,並且該destination
將直接在"Over"
之后以空終止,這就是為什么您看到上述行為的原因。
因此,在調用strncpy
myString
將等於:
"Over\0There"
解決方案
最簡單的解決方案是不要將尾部的空字節從"Over"
復制到strncpy
就像指定4
而不是5
一樣容易:
strncpy(myString, "Over", 4);
strncopy的文檔如下:
char * strncpy ( char * destination, const char * source, size_t num );
將源的前num個字符復制到目標。 如果在復制num個字符之前找到了源C字符串的末尾(由空字符表示),則將目標填充為零,直到總共寫入了num個字符為止。
通過調用strncpy(myString, "Over", 5)
,您實際上是將“ Over \\ n”復制到myString中。 您最好將最后一個參數作為strlen(source)調用strncpy。
嘗試以下
#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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.