所以我正在编写一些代码,这需要我将一个数字转换为二进制并将整个数字存储在一个字符数组中。
我试过了
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <cstdlib>
#include <windows.h>
#include <cmath>
#include <errno.h>
int main(int argc, char* argv[])
{
int fourtharg = atof(argv[4]);
int result = fourtharg;
int remainder = 0;
int aaa[10] = {};
char tab[10];
//cout << result << ", ";
for (int i = 8; i > 0; i--)
{
remainder = result % 2;
result = result / 2;
//cout << remainder;
aaa[i] = remainder;
}
//cout << "AAA is " << aaa;
//cout << endl;
std::ostringstream os;
for (int i = 8; i > 0; i--)
{
os << aaa[i];
//cout << aaa[i];
}
std::string str(os.str());
cout << fourtharg << ", "<< str << endl;
string binary = str;
return 0;
}
string binary = str;
成功转换为的行string
,但我希望将其作为字符数组。有什么建议?
现场演示。
更新:因此,在我们进行二进制转换后,我们有一个要写入的函数:
errno_t FileWriter(const char* filename, const char* strToWrite);
我们不允许更改该功能。也就是说,转换后的二进制文件应该上传到一个.txt
文件中,但由于const char* strToWrite
参数的原因,这无法完成,这就是为什么我尝试先转换为字符串,然后再转换为字符以查看是否可行。
所以在我们进行二进制转换后,我们有一个函数可以写入......也就是说,转换后的二进制文件应该上传到一个
.txt
文件,但是由于const char* strToWrite
参数的原因,这不能完成,这就是为什么我试图转换为字符串,然后到一个字符,看看它是否可以工作。
您可以通过以下方法将您std::string
的字符数据按原样传递给该函数std::string::c_str()
:
返回一个指向空终止字符数组的指针,该数组的数据与存储在字符串中的数据等效。
因此,您不需要实际的字符数组,例如:
FileWriter("filename", binary.c_str());
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句