2011-12-13 6 views
1

나는 초보자이며 파일에서 단어를 가져와 색인을 생성하고 각 단어를 한 번만 나열하고 매번 줄 번호를 표시하는 프로그램을 작성하려고합니다. 그 단어가 나타납니다. 나는지도를 사용하여 시도했지만 단어에 대한 줄 번호를 얻는 것이 불가능하다는 것을 알았다. 대신, 정수 벡터와 각 단어에 대한 문자열을 가진 구조체의 벡터를 사용하고 있습니다. 각 단어를 읽고 stringstream에 배치 한 다음 구조체의 문자열에 출력하려고합니다. 그런 다음 구조체의 벡터에 줄 번호와 push_back을 사용합니다. 모든 것을 구조체의 벡터에 저장하고 행 번호 벡터와 관련된 각 단어를 출력하려고합니다. 나는 아무데도 가지 않을 것이고 약간의 도움을 원할 것이다. Itd 많이 주셔서 감사합니다! 다음은 내 소스 코드입니다.벡터 구조체 벡터 및 문자열 올바르게 인쇄되지 않는다

#include <iostream> 
#include <string> 
#include <fstream> 
#include <map> 
#include <sstream> 
#include <vector> 
using namespace std; 



struct words { 
vector<int> lineNumbers; 
string word; 

}}; 프로그램의이 부분에 대한

int main() { 
ifstream inFile, testStream; 
ofstream outFile; 
string temp, choice, inFileName, outFileName, word, trash, word2, tempString; 
int idx = 0, count = 0, idxTwo = 0; 
bool outputOpened = false; 
//map <string,int> wordList;  
/map <string,int>::iterator wordIt;  
stringstream myStream(ios_base::in| ios_base::out); 

vector<words> myIndex; 
words data; 



for (;;) { 
    cout << "Options: "<< endl << "1. Index" << endl << "2. Quit" << endl 
    << "Please enter an option: "; 
    getline(cin, temp); 
    //cin >> temp; 
    //cin.ignore(8192, '\n'); 
    choice.resize(temp.length()); 
    transform(temp.begin(), temp.end(), choice.begin(), ::toupper); 
    if (choice.compare("INDEX") == 0 || choice.compare("1") == 0) { 
     do { 
      inFileName.clear(); 
      cout << "Index Program" << endl 
      << "==============" << endl << endl; 
      cout << "Input file name: "; 
      getline(cin, inFileName); 
      inFile.open(inFileName.c_str()); 
      if(inFile.fail()) { 
       cout << "Can't open file" << endl; 
       if(inFile.bad()) { 
        cout << "Bad" << endl; 
       } 
       inFile.clear(); 
      } 
     } 
     while (!inFile.is_open()); 
     do { 
      cout << "Output file name: "; 
      getline(cin, outFileName); 
      testStream.clear(); 
      testStream.open(outFileName.c_str()); 
      if(testStream.good()) { 
       cout << "That file already exists, try again" <<   endl; 
       testStream.clear(); 
       testStream.close(); 
      } 
      else { 
       testStream.clear(); 
       testStream.close(); 
       outFile.open(outFileName.c_str()); 
       if (outFile.good()) { 
        outputOpened = true; 
       } 
      } 
     } 
     while (!outputOpened); 

     while (getline(inFile, trash)){ 

      count++; 
      myStream << trash; 
      //myStream >> tempString; 

      while(myStream >> data.word) { 

       data.lineNumbers.push_back(count); 
       myIndex.push_back(data); 
      } 
     } 
     for (idx = 0; idx < myIndex.size(); idx++) { 
      outFile << "Word: "<< " "<< myIndex[idx].word << ", "; 
      for (idxTwo = 0; idxTwo < myIndex[idx].lineNumbers.size(); idxTwo++) { 
       outFile << "Found on lines " << " " << myIndex[idx].lineNumbers[idxTwo]; 
      } 
     } 
     inFile.close(); 
     outFile.close(); 
    } 
    else if (choice.compare("QUIT") == 0 || choice.compare("2") == 0) { 
     return 0; 
    } 
    else { 
     cout << temp << " is an unrecognized option, please try again" << endl; 
    } 
} 
return 0; 

} 
+1

사이트에 오신 것을 환영합니다! 실제 문제는 무엇입니까 (오류, 예기치 않은 동작, 다른 것들)? 우리가 가지고있는 것은 코드와 의도 = = – jadarnel27

+0

오 죄송합니다! 내 문제는 각 단어를 인쇄하지만 행의 모든 ​​행 번호를 인쇄하고 어느 단어가 어떤 행과 연결되는지를 구분하지 않습니다. 단어 1 1 단어 2 1,2 단어 3 1,2,3 등을 말할 것입니다. –

+0

감사합니다! 사람들이 문제가 무엇인지 빨리 알 수 있도록 질문 본문에 질문을 편집하십시오 (질문 바로 아래에있는 "편집"버튼 사용). 공부에 행운을 빈다 =) – jadarnel27

답변

0

: 당신은 글로벌 myStream를 사용하는

while (getline(inFile, trash)){ 
     count++; 
     myStream << trash; 
     //myStream >> tempString; 
     while(myStream >> data.word) { 
      // 2. 
      // data.lineNumbers.clear(); 
      data.lineNumbers.push_back(count); 
      myIndex.push_back(data); 
     } 
     // 1. add: 
     // myStream.clear(); 
    } 
  1. . 그러나이 myStream의 상태는 각 행을 처리 한 후에 데이터가 부족하여 상태가 좋지 않습니다. 다시 작동하려면 상태를 지워야합니다.

  2. data은 또한 현재 단어의 줄 번호뿐만 아니라 data.lineNumber에 모든 단어의 줄 번호를 저장합니다. 각각의 실행마다 지울 수도 있습니다.

0

귀하의 문제는 항상 각 단어를 vector<words>에 추가하고있는 것으로 보입니다.

아마도 원하는 것은 map<string, vector<int>>입니다. .insert를 사용하여 집합에 단어를 삽입하십시오. 이미 존재하는 경우에는 현재 행 번호를 값에 추가하십시오.

+0

나는지도를 작성하는 것을 끝내고 위대한 일을했다고 말하고 싶다. 나는지도가 그들 안에 벡터를 가질 수 있다는 것을 몰랐다. 고맙습니다! –

0

여기에 몇 가지 문제가 있습니다 :

while(myStream >> data.word) 루프 후 myStream.clear();를 추가합니다. 다음 줄의 끝에 "\ n"

추가는 새 줄에 인쇄 :

outFile << "Found on lines " << " " << myIndex[idx].lineNumbers[idxTwo]<<"\n"; 

또한, 다음과 같은 중첩 루프는 당신에게 정확한 결과를 제공하지 않습니다. 줄 번호가 늘어나고 "줄에 서 발견"된 인쇄물을 계속 보관합니다.

for (idx = 0; idx < myIndex.size(); idx++) { 
outFile << "Word: "<< " "<< myIndex[idx].word << ", "; 
    for (idxTwo = 0; idxTwo < myIndex[idx].lineNumbers.size(); idxTwo++) { 
    outFile << "Found on lines " << " " << myIndex[idx].lineNumbers[idxTwo]<<"\n"; 
    }