Hello everyone I'm having trouble writing part of a vector to a file. I'm getting this error:

main.cpp:287: error: cannot convert `std::basic_string<char, std::char_traits<char>, std::allocator<char> >' to `const char*' for argument `2' to `int fprintf(FILE*, const char*, ...)'

This is part of my code:

ListViewTextItem.begin();
FILE * pFile;
  pFile = fopen ("myfile.txt","w");
for( int i = 0; i < ListViewTextItem.size(); i++ ) {
fprintf(pFile, ListViewTextItem[i] );
 }
fclose (pFile);

What's the problem with and how do I fix it???

Dani AI

Generated

As hinted, the root issue is mixing C++ string objects with C stdio calls. Those C functions expect C-style data and a format string; giving them a C++ object produces a type mismatch and can lead to undefined behavior if the string contains percent signs. 's suggestion to prefer C++ streams is a cleaner, safer route.

A straightforward, modern fix is to use RAII-style C++ I/O. Example patterns that avoid manual FILE* management:

#include <fstream>

std::ofstream out("myfile.txt");
if (!out) {
    // handle error (permissions, path, etc.)
}
for (const auto &elem : ListViewTextItem)
    out << elem << '\n';

or, using the STL algorithms:

#include <fstream>
#include <iterator>
#include <algorithm>

std::ofstream out("myfile.txt");
std::copy(ListViewTextItem.begin(), ListViewTextItem.end(),
          std::ostream_iterator<std::string>(out, "\n"));

Troubleshooting notes: verify the container element type (std::string vs wide string vs framework string) and convert appropriately before writing; check the file open result and any filesystem permissions; if you must use C fprintf, always supply an explicit format specifier so the library doesn't interpret percent sequences from your data (and convert the C++ string to a C-style buffer first). For Unicode data, use wide-character streams or convert to UTF-8. For reference on the C++ and C APIs, see cppreference on std::ofstream and fprintf: std::ofstream and fprintf.

Recommended Answers

All 2 Replies

What kind of an object is ListViewTextItem?

The second argument to fprintf() is a char*, not a c++ class. fprintf() doesn't know a thing about c++ or objects.

Since this is a C++ program, use the C++ I/O mechanisms.

Or to fix the immediate line of code. fprintf(pFile, ListViewTextItem[i].c_str() );

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.