C++:使用 fstream、map 和输出
C++: using fstream, maps, and output
我正在尝试打开一个文本文件,然后从中读取每一行,并将每个单词出现映射到它所在的行号。然后,我想打印地图。这是我的代码:
#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;
}
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 请解释"函数1(p1,p2,p3);"的输出
- C++:将控制台输出存储在宏中更好吗
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 使用一个考虑到std::map中键值的滚动或换行的键
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 为什么我的代码在输出中增加了93天
- 如何从void函数输出字符串
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- AES加密到解密未正确输出
- Map.find()如何工作,查看输出的组件
- 使用d3d11_mapped_subresource和map/umap时,混合纹理输出
- C++:使用 fstream、map 和输出
- 嵌套 std::map 的输出存在问题
- ofstream 输出 std::map<UnicodeString, UnicodeString> 产生地址而不是字符串
- 在c++中使用map时输出顺序错误
- 数据将奇怪的数字输出到文件,MAP C++