2013-05-29 3 views
0

단어를 키로 포함하는지도를 반복하고 각 단어에 숫자가 배열되어 에 저장되어있는 숫자가 발견되었습니다. 해당 정보를 .txt 파일로 출력하는 데 문제가 있습니다.ofstream 문제는 어떻게 해결합니까?

가비지가 파일에 나타나고 프로그램이 충돌하면 충분하지 않습니다.

몇 가지 간단한 테스트를 거친 끝에 최종 정보가 .txt 파일로 출력 될 때 오류가 명백한 위치에서 발생한다는 것을 알았습니다.

정보 검색과 관련하여 유일한 관련 정보는 누군가가 ofstream을 루프에 사용해서는 안된다는 말입니다. 어떻게 든 오버플로를 일으킬 수 있다고 생각하십니까? 어쩌면 흘러 나오지 않는 것이 있을까요?

왜 잘못 되었습니까? 어떻게 해결할 수 있습니까?

//FINAL OUTPUT TO A FILE, CREATING A NEW .txt FILE 
ofstream filehandle; 
filehandle.open("result.txt",ios::out); 

if(filehandle.is_open()) 
{ 
    for(map<string, vector<int> >::const_iterator a = line_num_by_word.begin();a!=line_num_by_word.end();++a) 
    { 
     filehandle << "The word " << "\"" << a->first << "\"" << " is present on: \n"; 

     vector<int>::const_iterator int_vec_c_it = a->second.begin(); 

     while(int_vec_c_it != a->second.end()) 
     { 
      vector<int>::const_iterator in_front_of_it = int_vec_c_it+1; 
      //count the number of times 
      int counter = 1; 
      while(*(int_vec_c_it)==*(in_front_of_it)) 
      { 
       ++counter; 
       ++in_front_of_it; 
      } 
      filehandle << " line " << *(int_vec_c_it) << "-" << counter << " times "; 

      int_vec_c_it = in_front_of_it; 
     } 
     filehandle << "\n"; 
    } 
}else cout << "no output" <<endl; 
+4

한 끝에서 끝 반복자를 역 참조하는 것은 정의되지 않은 동작이며 'in_front_of_it'을 사용하여 수행하는 것과 정확히 같습니다. – chris

답변

1

A-> 제()가 끝나기 전에 온 (인) it_front_of_it가 종료한다(). 그런 다음에 당신은 그것을 역 참조하십시오.

while(*(int_vec_c_it)==*(in_front_of_it)) 
관련 문제