【问题标题】:convert int to const char* in order to write on file将 int 转换为 const char* 以便写入文件
【发布时间】:2011-10-28 21:04:57
【问题描述】:

我在 C++ 中有以下代码,我想将整数转换为 const char* 以便写入文件。我尝试了 itoa 或 sstream 函数,但它不起作用。

FILE * pFile;
pFile = fopen ("myfile.txt","w");

int a = 5;

fputs (&a,pFile);
fclose (pFile);

提前致谢

【问题讨论】:

  • “不工作”没有帮助。我假设您希望人们告诉您的不仅仅是“修复它”,对吧?

标签: c++ char constants int


【解决方案1】:

fputs 的第一个参数是char*,所以你显示的代码显然是不正确的。

你说I tried itoa or sstream functions but it's not working.,但那些是解决方案,他们没有理由不工作。

int a = 5;

//the C way
FILE* pFile = fopen("myfile.txt","w");
char buffer[12];
atoi(a, buffer, 10);
fputs(buffer, pFile); 
fclose (pFile);
//or
FILE* pFile = fopen("myfile.txt","w");
fprintf(pfile, "%d", a);
fclose(pfile);

//the C++ way
std::ofstream file("myfile.txt");
std::stringstream ss;
ss << a;
file << ss.str();
//or
std::ofstream file("myfile.txt");
file << a;

【讨论】:

  • 我的错误是我试图同时管理 fputs 和 ofstream。非常感谢。
  • “不要越过溪流!”对于ofstream,最接近fputs 的是ofstream::write(const char_type *_Str, streamsize _Count)
【解决方案2】:

尝试itoa(a) 它将 i nt to a 阵列转换为itoa

【讨论】:

  • 也有相反的atoi,即array 和int
  • 我更喜欢 strtol 的字符串到整数(long 真的)路线。它可以让我设置数字基数,我可以设置基数 0 来表示“从前缀中找出它”(这让我可以解析 0x1234 等)。它给了我一个指向数字末尾字符的指针,我可以在其中尝试解析单位。
  • itoa 不是标准函数。来自the documentation:“此函数未在 ANSI-C 中定义,也不是 C++ 的一部分,但某些编译器支持。”
【解决方案3】:

fprintf 有什么问题?或者snprintf 然后fputs 结果。

【讨论】:

  • 养成使用snprintf而不是sprintf的习惯。
【解决方案4】:

使用类型转换。你可以使用boost::lexical_cast

一旦在字符串中,你可以使用 c_str() 成员函数来获取一个 const char *

【讨论】:

    猜你喜欢
    • 2015-11-23
    • 1970-01-01
    • 2021-11-09
    • 2014-09-20
    • 1970-01-01
    • 2013-10-16
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    相关资源
    最近更新 更多