텍스트 파일을 열려고 시도하고 있으며, 여기에서 각 행을 읽고 각 단어 어커런스가있는 행 번호에 매핑합니다. 그런 다음지도를 인쇄하고 싶습니다. 내 코드는 다음과 같습니다.C++ : fstream, 맵핑 및 출력 사용
#include <map>
#include <set>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main(){
std::map<string, set<int>> myMap;
ifstream myFile;
string myLine ="";
int lineNum = 0;
stringstream myStream;
string myWord ="";
set<int> mySet;
myFile.open("myTextFile.txt");
if(myFile.is_open()){
while (!myFile.eof()){
getline(myFile, myLine);
myStream.str(myLine);
++lineNum;
while (!mySStream.eof())
{
myStream >> myWord;
myMap[myWord].insert(lineNum);
}
myStream.clear();
}
}
myFile.close();
// at this point, I expect everything to have been mapped
// mapping each word occurrence to a line
//I now want to print the map but out does not work, and I need to use an iterator
//I have tried this:
map<string, set<int>>::iterator iter;
for (iter = myMap.begin(); iter != myMap.end(); ++iter)
{
cout << "Key: " << iter->first << endl << "Values:" << endl;
set<int>::iterator setIter;
for (setIter = iter->second.begin(); setIter != iter->second.end(); ++setIter)
cout << " " << *setIter<< endl;
}
return 0;
}
출력이 없습니다. 왜 안돼? 둘째, 모든 것이 올바르게 매핑되고 있습니까?
'while (! myFile.eof()) Nope. – ildjarn
[왜 루프 상태에서 iostream :: eof가 잘못된 것으로 간주 되는가?] (0120-13753) –
[std :: endl'의 과도한 사용을 중지하십시오] (http : //kuhllib.com/2012/01/14/stop-excessive-use-of-stdendl/) –