2016-07-15 91 views
-1

我有这样的代码:写格式的文本文件 - C++

 printf("GPU: %ic SYSTEM: %ic CPU: %ic HDD: %ic ",temp[0],temp[1],temp[2],temp[7]); 
     ofstream temp_file; 
     temp_file.open("D:\\localhost\\xampp\\htdocs\\monitor\\temps.json"); 
     temp_file << fprintf("\"{\"GPU\": [%ic], \"System\": [%ic], \"CPU\": [%ic], \"HDD\": [%ic]}\"", temp[0],temp[1],temp[2],temp[7]); 
     temp_file.flush(); 
     temp_file.close(); 

,我得到错误“不能将 '为const char *' 到 'FILE * {又名_iobuf *}' 的说法 '1'到'int fprintf(FILE *,const char *,...)'

temp变量是一个int,并且代码的第一行成功地打印出格式化文本。一个文件?

+0

如果它们很容易使用,为什么不使用'FILE *'和'fopen()'? – MikeCAT

+0

你想使用什么['snprintf()'](http://linux.die.net/man/3/snprintf)。 – MikeCAT

+0

检查fprintf采用的参数。比较你的代码。再次阅读错误消息。另外,避免像printf这样的传统C函数,因为它们不是类型安全的,而且很容易创建未定义的行为错误。只需使用C++流。 – hyde

回答

1

您滥用fprintf()

fprintf()返回int并预计其第一个参数是一个FILE *per the documentation

int fprintf(FILE *restrict stream, const char *restrict format, ...); 

你需要先使用s[n]printf()如果这就是你想要走的路线来格式化文本 - 让C型字符串,并将其写入C++ ofstream

char buffer[ BUF_SIZE ]; 
snprintf(buffer, sizeof(buffer), 
    "\"{\"GPU\": [%ic], \"System\": [%ic], \"CPU\": [%ic], \"HDD\": [%ic]}\"", 
    temp[0], temp[1], temp[2], temp[7]); 

... 

temp_file << buffer; 

... 

还有许多其他的方式来格式化C++的产量。

+0

谢谢,这对我有用 –

0

这个temp_file << fprintf("\"{\"GPU\": [%ic], \"System\": [%ic], \"CPU\": [%ic], \"HDD\": [%ic]}\"", temp[0],temp[1],temp[2],temp[7]);是错误的。你不能合并ofstreamfprintf - u一个或另一个。

要写入格式化输出到您使用io manipulators,你不需要做什么特别的输出整数流,字符串,双打等

+0

_“你不能合并ofstream和fprintf“_严格地说这是错误的陈述,为什么不呢?为什么不这样做呢?为什么要这样做,而应该怎么做 - 不同讨论的主题 – mvidelgauz

+0

'fprintf'返回写入的字符数。正在输出打印的字符数,所以是的,'fprintf'可以和流插入操作符一起使用。 –

+0

是的,是的,但不是OP的意图,我相信你们都很清楚。 –

1

使用boost::format

cout << boost::format("\"{\"GPU\": [%1%], \"System\": [%2%], \"CPU\": [%3%], \"HDD\": [%4%]}\"") % temp[0] % temp[1] % temp[2] % temp[3]; 
+2

Boost这个问题的矫枉过正,就像使用jackhamm一样呃让花生脱壳。 –

+0

@AndrewHenle,在不知道问题的范围的情况下,评论真的很难,而且这些日子真的很难提升? – Nim

+0

不知道问题的范围,推荐Boost更加矫枉过正。 –

0

fprintf的第一个参数必须是指向标识流而不是temp [0](GPU)的FILE对象的指针。

C库函数int fprintf(FILE * stream,const char * format,...)将格式化的输出发送到流。