fcl*_*pez 0 c c++ string printf vector
可能重复:
c ++ - 字符串上的printf打印出乱码
我想写几个字符串来存档.字符串是
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
Run Code Online (Sandbox Code Playgroud)
我首先想将每一行存储为字符串数组的元素,然后调用相同的字符串数组并将其元素写入文件.
#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;
}
Run Code Online (Sandbox Code Playgroud)
格式说明符"%s"期望C样式的空终止字符串,而不是std::string.改成:
fprintf(fp_w, "%s", vec[j].c_str());
Run Code Online (Sandbox Code Playgroud)
由于这是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];
}
Run Code Online (Sandbox Code Playgroud)
同样,ifstream用于输入.发布的代码有可能的缓冲区溢出:
char line[100];
...
if(fgets(line, 256,fp_r) != NULL)
Run Code Online (Sandbox Code Playgroud)
line可以存储最多的100字符,但fgets()表明它可以容纳256.使用std::getline()消除了这种潜在的危险,因为它填充了std::string:
std::ifstream in(fname_r);
std::string line;
while (std::getline(in, line)) vec.push_back(line);
Run Code Online (Sandbox Code Playgroud)