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;
}
The format specifier
"%s"expects a C-style null terminated string, not astd::string. Change to:As this is C++, you should consider using
ofstreaminstead which are type-safe and acceptstd::stringas input:Equally, use
ifstreamfor input. The posted code has a potential buffer overrun:linecan store a maximum of100characters but thefgets()is stating that it can hold256. Usingstd::getline()removes this potential hazard as it populates astd::string: