gpt4 book ai didi

C++:使用 fstream、映射和输出

转载 作者:太空宇宙 更新时间:2023-11-04 11:24:25 26 4
gpt4 key购买 nike

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

#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 位,而是将 getlines 移到了 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;

}

关于C++:使用 fstream、映射和输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27162154/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com