C++:使用 fstream、map 和输出

C++: using fstream, maps, and output

本文关键字:map 输出 fstream 使用 C++      更新时间:2023-10-16

我正在尝试打开一个文本文件,然后从中读取每一行,并将每个单词出现映射到它所在的行号。然后,我想打印地图。这是我的代码:

#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;
}

我没有输出。为什么不呢?其次,是否一切都被正确映射?

由于我不在我的开发机器上,所以我无法对其进行测试。如果我了解您要做什么,这应该有效。基本上,我没有检查 EOF 位,而是将获取行移动到 while 循环中。std::getline 将在读取整个文件后退出循环!

#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 (getline(myFile, myLine)){
        myStream.str(myLine);
        ++lineNum;
        while (myStream >> myWord)
        {
            myMap[myWord].insert(lineNum);    
        }           
        myStream.clear();
   }
    myFile.close();
}
else
{
    std::cout << "Unable to open file!" << std::endl;
}
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;
}