2013-10-27 88 views
2
string replace_strings (FILE *in, FILE *out, char *what, char *repl) 
{ 
    int x = strlen(what); 
    int z = strlen(repl); 
    string newWhat(what, x); 
    string newRepl(repl, z); 
    char c; 
    char *str; //наш буффер 
    int i = 0; 
    size_t found; 

这是一个错误的决定做这样的,我知道导致此分段错误的原因是什么?

while(!feof(in)) 
    { 
     while((c!='\0') && (i<=255)) 
     { 
      str[i] = fscanf(in, "%c", c); 
      i++; 
     } 
     string newStr (str, i); 
     while(found != string::npos) 
     { 
      found = newStr.find(newWhat); 
      newStr.replace(found, newWhat.length(), newRepl); 
     } 

     fprintf(out, "%s", newStr.c_str()); 

返回段错误,有什么不对?我该怎么办?帮助我们

+1

什么是调试器告诉你有关错误的来源?此外,你**总是**需要检查输入是否成功** **之后尝试读取的东西。 –

+2

你不初始化'c',并且你不初始化'str',所以会发生任何事情。 –

+0

如果您没有将C I/O与C++功能混合,生活会更容易。例如,'std :: fstream'与'std :: string'相比'fprintf'更好。 –

回答

2

您必须为str分配内存。使用stringstream,并忘记笨拙的缓冲区。

+0

读取数据时,你想使用'std :: istringstream',而不是'std :: stringstream'。 –

+0

此外,当从文件或键盘读取数据时,使用'std :: getline'和'std :: string'。不要混用'std :: string'和'char *'。坚持一个或另一个。 –

相关问题