Reputation: 301
I have this code:
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();
and I get the error "cannot convert 'const char*' to 'FILE* {aka _iobuf*}' for argument '1' to 'int fprintf(FILE*, const char*, ...)'
the temp variable is an int, and the first line of the code does successfully print out the formatted text. How do i push that text to a file?
Upvotes: 0
Views: 8482
Reputation: 1109
The first parameter of fprintf must be the pointer to a FILE object that identifies the stream instead of temp[0] (GPU).
The C library function int fprintf(FILE *stream, const char *format, ...) sends formatted output to a stream.
Upvotes: 0
Reputation: 1
You are misusing fprintf()
.
fprintf()
returns an int
and expects its first argument to be a FILE *
, per the documentation:
int fprintf(FILE *restrict stream, const char *restrict format, ...);
You need to format your text first using s[n]printf()
if that's the route you want to take - making a C-style string and writing it to a 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;
...
There are many other ways to format output in C++, too.
Upvotes: 1
Reputation: 33655
Use boost::format
:
cout << boost::format("\"{\"GPU\": [%1%], \"System\": [%2%], \"CPU\": [%3%], \"HDD\": [%4%]}\"") % temp[0] % temp[1] % temp[2] % temp[3];
Upvotes: 1
Reputation: 31465
This temp_file << fprintf("\"{\"GPU\": [%ic], \"System\": [%ic], \"CPU\": [%ic], \"HDD\": [%ic]}\"", temp[0],temp[1],temp[2],temp[7]);
is wrong. You cannot combine ofstream
and fprintf
- use one or the other.
To write formatted output to a stream you use io manipulators and you don't need to do anything special to output integers, strings, doubles etc.
Upvotes: 0