我是一個開始的C++學生,並且正在嘗試編寫一個程序,該程序會在文件中佔用一個單詞並對其進行索引,每次只列出一個單詞並顯示每次的行數那個詞出現。我曾嘗試使用地圖,但我發現無法獲取單詞的行號。相反,我使用的結構向量具有整數向量和每個單詞的字符串。我正在嘗試讀取每個單詞,將其放入一個字符串流中,然後將其輸出到結構體中的字符串中。然後我把行號和push_back到結構中的向量中。然後我將所有內容保存到結構的向量中,並嘗試打印出與行號向量關聯的每個單詞。我無處可去,希望得到一些幫助。非常感謝!這裏是我的源代碼:向量和字符串結構的向量不正確打印
#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;
}
歡迎來到本網站!你遇到的實際問題是什麼(錯誤,意外行爲,其他事情)?我們所有的是你的代碼和你的意圖=) – jadarnel27
哦對不起!我的問題是,它會打印每個單詞,但它會在一行中打印所有的行號,並且不會接近分隔哪個單詞與哪些行。它會說類似word1 1 word2 1,2 word3 1,2,3等。 –
感謝您的更新!隨意將其編輯到問題主體中(使用問題下方的「編輯」按鈕),以便人們可以快速查看問題所在。祝你好運在你的學習=) – jadarnel27