我是一个开始的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