Я новичок в C ++ и могу динамически добавлять слова из файла в векторный массив, но я хочу взять каждое слово и выяснить, сколько раз это слово встречается в файле и печатать слово только один раз.и перечислите номер строки каждый раз, когда это происходит.Я не уверен, куда идти от моего вектора слов.Есть ли способ сравнить каждый строковый элемент?Вот мой исходный код:
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>#include
using namespace std;
int main() {
ifstream inFile, testStream;
ofstream outFile;
vector<string> words;
string temp, choice, inFileName, outFileName, word, trash;
int idx = 0, lineCount = 0;
bool outputOpened = false;
stringstream wordStream;
for (;;) {
cout << "Options: "<< endl << "1. Index" << endl << "2. Quit" << endl
<< "Please enter an option: ";
getline(cin, temp);
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 (inFile.peek() != EOF) {
getline(inFile,word, ' ');
lineCount++;
words.push_back(word); // now the vector 'words' contains all words in the file
}
for (idx = 0; idx < words.size(); idx++) {
outFile << words[idx] << endl;
}
}
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;
}