Обновление и исправление: я исправил проблему, вызвавшую сообщение об ошибке. Огромное спасибо пользователю PaulMcKenzie за то, что он помог мне понять, о чем говорит сообщение об ошибке! думаю, что они называются), он разбился. Я изменил свой код, чтобы учесть это, и теперь он совсем не падает! Еще одно огромное спасибо пользователю ihavenoidea за помощь в понимании мультимножеств! Моя программа теперь работает так, как она должна!
Исходное сообщение:
**** Я ОЧЕНЬ новичок в C ++, поэтому любая помощь приветствуется! ****
Хорошо, я пытаюсь использовать мультимножество для сортировки слов, чтобы увидеть, сколько раз слово появляется в тексте. Сначала моя программа принимает файл, затем читает слова и удаляет любые знаки препинания, а затем помещает его в мультимножество. После этого предполагается поместить результаты в текстовый файл с именами пользователей.
Моя первая проблема заключается в том, что мультимножество, кажется, создает более одного элемента для одного и того же слова (например: в одном из моих тестов я видел (4), перечисленные в текстовом документе 3 раза подряд вместо одного время).
Моя вторая проблема заключается в том, что когда я пытаюсь читать большие текстовые документы (я использую рассказ Джона Коллирса «Бутылочная вечеринка» http://ciscohouston.com/docs/docs/greats/bottle_party.html, чтобы проверить его), моя программа полностью падает, но не падает, когда я протестируйте его с меньшим текстовым документом (маленькое существо, скажем, около 5-10 строк текста). Я использую Visual Studios и (еще раз я новичок в Visual Studios), я не знаю, что пытается сообщить мне сообщение об ошибке, но оно говорит:
После выбора повтора:
Как всегда, любая помощь очень ценится.
Код здесь:
#include <iostream>
#include <string> //for strings
#include <fstream> //for files
#include <set> //for use of multiset
using namespace std;
string cleanUpPunc(string);
//Global variables
multiset <string> words; //will change back to local variable later
int main() {
//Starting variables
string fileName1 = "", fileName2 = "", input = "", input2 = ""; //To hold the input file and the file we wish to print data to if desired
ifstream fileStream; //gets infor from file
//Program start
cout << "Welcome to Bags Program by Rachel Woods!" << endl;
cout << "Please enter the name of the file you wish to input data from: ";
getline(cin, fileName1);
//Trys to open file
try {
fileStream.open(fileName1);
if (!fileStream) {
cerr << "Unable to open file, please check file name and try again." << endl;
system("PAUSE");
exit(1);
}
while (fileStream >> input) {
input2 = cleanUpPunc(input); //sends the input word to check for punctation
words.insert(input2); //puts the 'cleaned up' word into the multiset for counting
}
fileStream.close();
//Sends it to a text document
cout << "Please name the file you would like to put the results into: ";
getline(cin, fileName2);
ofstream toFile; //writes info to a file
//Code to put info into text file
toFile.open(fileName2);
if (toFile.is_open()) {
multiset<string>::iterator pos;
for (pos = words.begin(); pos != words.end(); pos++) {
toFile << *pos << " " << words.count(*pos) << endl;
}
toFile.close();
cout << "Results written to file!" << endl;
}
else {
cout << "Could not create file, please try again." << endl;
}
}catch (exception e) {
cout << "Stop that. ";
cout << e.what();
}
cout << "Thanks for using this program!" << endl;
system("PAUSE");
return 0;
}
string cleanUpPunc(string maybe) {
//Takes out puncuation from string
//Variables
string takeOut = maybe;
//Method
for (int i = 0, len = maybe.size(); i < len; i++) {
if (ispunct(takeOut[i])) {
takeOut.erase(i--, 1);
len = takeOut.size();
}
}
return takeOut;
}