簡體   English   中英

將C ++字符串轉換為C char數組以寫入二進制文件

[英]C++ string to C char array for writing to binary file

我正在嘗試向二進制文件寫入字符串或從二進制文件讀取字符串,但是我不明白為什么sizeof(t)返回4。

//write to file
ofstream f1("example.bin", ios::binary | ios::out);
string s = "Valentin";
char* t = new char[s.length()+1];
strcpy(t, s.c_str());
cout << s.length()+1 << " " << sizeof(t) << endl; // prints 9 4
for(int i = 0; i < sizeof(t); i++)
{
    //t[i] += 100;
}
f1.write(t, sizeof(t));
f1.close();

// read from file
ifstream f2("example.bin", ios::binary | ios::in);
while(f2)
{
    int8_t x;
    f2.read((char*)&x, 1);
    //x -= 100;
    cout << x;  //print Valee
}
cout << endl;
f2.close();

放入char *數組t中的大小無關緊要,代碼始終將“ 4”作為其大小打印。 寫入超過4個字節的數據該怎么辦?

這是簡單的編寫代碼的方法

//write to file
ofstream f1("example.bin", ios::binary | ios::out);
string s = "Valentin";
f1.write(s.c_str(), s.size() + 1);
f1.close();

編輯OP實際上需要這樣的東西

#include <algorithm> // for transform

string s = "Valentin";
// copy s to t and add 100 to all bytes in t
string t = s;
transform(t.begin(), t.end(), t.begin(), [](char c) { return c + 100; });
// write to file
ofstream f1("example.bin", ios::binary | ios::out);
f1.write(t.c_str(), t.size() + 1);
f1.close();

sizeof(char*)打印指向一個或多個char的指針使用的大小。 在您的平台上是4。

如果需要字符串的大小,則應使用strlen 或者,簡單來說就是s.length()

char *t是指針,而不是數組,因此sizeof將返回計算機上指針的大小,顯然是4個字節。

確定C樣式字符串長度的正確方法是包含<cstring>並使用std::strlen

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM