我想要做的是將字符串轉換爲const char *。理想情況下,我可以使用「const char * myConstChar = myString.c_str()」,但正如下面的示例所示;它不適用於二進制數據:將字符串轉換爲const char *(使用二進制數據)
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <string.h>
using namespace std;
int main(){
string myString; // This need to be string
ifstream infile;
const char* myConstChar; // This need to be const char*
infile.open("binary.bin");
if(infile){
while(getline(infile, myString)){
std::cout << "Data: " << myString << " string length: ";
std::cout << myString.length() << "\n";
myConstChar = myString.c_str();
std::cout << "const char Data: " << myConstChar;
std::cout << " const char length: "<< strlen(myConstChar) <<"\n";
}
}
infile.close();
return 0;
}
這將返回「字符串長度:13」和「常量字符長度:3」。
當使用myString.c_str()
將字符串轉換爲const char*
時,顯然存在一些數據丟失!
如何將字符串轉換爲常量字符而不丟失二進制數據?
爲什麼使用字符串來讀取二進制數據? – shf301
我建議你切換到'std :: vector'。 –
jrok
它是如何[標籤:C]問題? o.O – Griwes