2012-08-29 28 views
0

可能重複:
c++ - printf on strings prints gibberishfprintf中,字符串和向量

我想寫一些字符串文件。字符串是

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 

我第一想用來存儲每行作爲一個字符串數組的元素,然後調用相同的字符串陣列和寫其到文件元件。

#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

http://stackoverflow.com/questions/3634766/c-printf-on-strings-prints-gibberish –

+2

你正在用C++編寫C代碼。停下來。 – rubenvb

回答

7

格式說明"%s"預計C風格空終止字符串,而不是std::string。更改爲:

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

由於這是C++,你應該考慮使用ofstream代替其是類型安全,並接受std::string輸入:

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]; 
} 

同樣,使用ifstream輸入。張貼的代碼有一個潛在的緩衝區溢出:

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

line最多100字符可以存儲,但fgets()是說,它可以容納256

std::ifstream in(fname_r); 
std::string line; 
while (std::getline(in, line)) vec.push_back(line); 
+0

謝謝!我很感激幫助 – fclopez

0

在這種情況下VEC [j]爲的std :: string對象:使用std::getline()作爲它填充一std::string移除此潛在危險。但fprintfs需要c樣式空終止的字符串。

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

所有你需要的從std :: string得到指向c風格字符串的指針。這是可能使用c_str方法:

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

在任何情況下,你混合C++和C代碼。它很醜。使用std :: fstream更好。