0

Possible Duplicate:
c++ - printf on strings prints gibberish

I would like to write several strings to file . The strings are

37 1 0 0 0 0 15 1 0 0 0 0 33 1 0 0 0 0 29 1 0 0 0 0 18 1 0 0 0 0 25 1 0 0 0 0 

I first would like to store each line as elements of a string array, then call the same string array and write its element to file.

#include <stdio.h> #include <vector> #include <string> using namespace std; int writeFile() { char line[100]; char* fname_r = "someFile_r.txt" char* fname_w = "someFile_w.txt"; vector<string> vec; FILE fp_r = fopen(fname_r, "r"); if(fgets(line, 256,fp_r) != NULL) { vec.push_back(line); } FILE fp_w = fopen(fname_w, "w"); for(int j = 0; j< vec.size(); j++) { fprintf(fp_w, "%s", vec[j]); // What did I miss? I get funny symbols here. I am expecting an ASCII } fclose(fp_w); fclose(fp_r); return 0; } 
1
  • 2
    You're writing C code in C++. Stop it. Commented Aug 29, 2012 at 10:02

2 Answers 2

7

The format specifier "%s" expects a C-style null terminated string, not a std::string. Change to:

fprintf(fp_w, "%s", vec[j].c_str()); 

As this is C++, you should consider using ofstream instead which are type-safe and accept std::string as input:

std::ofstream out(fname_w); if (out.is_open()) { // There are several other ways to code this loop. for(int j = 0; j< vec.size(); j++) out << vec[j]; } 

Equally, use ifstream for input. The posted code has a potential buffer overrun:

char line[100]; ... if(fgets(line, 256,fp_r) != NULL) 

line can store a maximum of 100 characters but the fgets() is stating that it can hold 256. Using std::getline() removes this potential hazard as it populates a std::string:

std::ifstream in(fname_r); std::string line; while (std::getline(in, line)) vec.push_back(line); 
Sign up to request clarification or add additional context in comments.

Comments

0

In this case vec[j] is std::string object. But fprintf with s expects c-style null-terminated string.

for(int j = 0; j< vec.size(); j++) { fprintf(fp_w, "%s", vec[j]); } 

All you need get pointer to c-style string from std::string. It's possible using c_str method:

for(int j = 0; j< vec.size(); j++) { fprintf(fp_w, "%s", vec[j].c_str()); } 

In any case, you mixes C++ and C code. It's ugly. Using of std::fstream is better.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.