我是一名初学 C++ 的学生,我正在尝试编写一个程序,在文件中获取一个单词并为其编制索引,只列出每个单词一次并显示该单词每次出现时的行号。我试过使用 map ,但我发现无法获取单词的行号。相反,我使用的是一个结构 vector ,每个单词都有一个整数 vector 和一个字符串。我正在尝试读取每个单词,将其放入字符串流中,然后将其输出到结构中的字符串中。然后我获取行号并将其 push_back 到结构中的 vector 中。然后我将所有内容保存到结构的 vector 中,并尝试打印出与行号 vector 关联的每个单词。我无处可去,需要一些帮助。非常感谢!这是我的源代码:
#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;
}
最佳答案
您的问题似乎是您总是将每个单词附加到 vector<words>
.
您可能想要的是 map<string, vector<int>>
.使用 .insert 将单词插入到集合中,如果它已经存在,则只需将当前行号附加到值。
关于c++ - Vector 和 String 结构的 vector 未正确打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8483530/