我想写几个字符串来归档。字符串是
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;
}发布于 2012-08-29 09:52:54
格式说明符"%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::getline()在填充std::string时消除了这个潜在的危险。
std::ifstream in(fname_r);
std::string line;
while (std::getline(in, line)) vec.push_back(line);发布于 2012-08-29 09:56:26
在本例中,vecj是std::string对象。但是fprintf和s需要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更好。
https://stackoverflow.com/questions/12175186
复制相似问题