C++ fprintf、字符串和向量

C++ fprintf、字符串和向量,c++,c,string,vector,printf,C++,C,String,Vector,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 我首先希望将每一行存储为字符串数组的元素,然后调用同一个字符串数组并将其元素写入文件 #include <stdio.h> #include <vector> #include <string> using namespace std; int write

可能重复:

我想在文件中写入几个字符串。弦是

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;
}
#包括
#包括
#包括
使用名称空间std;
int writeFile(){
字符行[100];
char*fname\u r=“someFile\u r.txt”
char*fname_w=“someFile_w.txt”;
向量向量机;
文件fp_r=fopen(fname_r,“r”);
如果(fgets(第256行,fp_r)!=NULL){
矢量推回(直线);
}
文件fp_w=fopen(fname_w,“w”);
对于(int j=0;j
格式说明符
“%s”
需要以C样式的null结尾的字符串,而不是
std::string
。改为:

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

这是C++,应该考虑使用类型安全的,并且接受<代码> STD::String < /Cord>作为输入:

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];
}
line
最多可以存储
100
个字符,但是
fgets()
声明它可以存储
256
。在填充
std::string
时,使用可消除此潜在危险:

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

在本例中,vec[j]是std::string对象。但是带有
s
fprintf
需要c样式的以null结尾的字符串

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

无论如何,你混合C++和C代码。很难看。使用STD::FSRESH更好。

你正在用C++编写C代码。住手,谢谢!我感谢你的帮助
for(int j = 0; j< vec.size(); j++) {
    fprintf(fp_w, "%s", vec[j]); 
}
for(int j = 0; j< vec.size(); j++) {
    fprintf(fp_w, "%s", vec[j].c_str()); 
}