dictionary - Putting words from a file into a hash map (c++) -
so, have text file quite long (10k+ words) , trying put each unique word hash map using standard map library.
i have while loop reading each word file. problem is, while loop never seems end. put if statement in loop if reached eof() break loop. still not end. here code far:
#include <iostream> #include <map> #include <string> #include <fstream> #include <cctype> using namespace std; string lowercase(string isupper); void main() { //create hash map map<string, int> stringcounts; //temp string string nextstring; //import file/write file ofstream writefile; ifstream goosefile; //open file read goosefile.open("goose.txt"); if (goosefile.is_open()) { //read file word word while (goosefile >> nextstring) { //works not change //check punctuation (int = 0; < nextstring.length(); i++) { //works not change if (nextstring[i] == ',' || nextstring[i] == '!' || nextstring[i] == ';' || nextstring[i] == '-' || nextstring[i] == '.' || nextstring[i] == '?' || nextstring[i] == ':' || nextstring[i] == '"' || nextstring[i] == '(' || nextstring[i] == ')' || nextstring[i] == '_' || nextstring[i] == '\'') { nextstring.erase(i, i); i--; } } //put lowercase nextstring = lowercase(nextstring); //works not change //cout << nextstring << endl; //increment key value stringcounts[nextstring]++; if (goosefile.eof()) break; } } //close current file goosefile.close(); cout << "i got here!"; //now print output file writefile.open("output.txt"); if (writefile.is_open()) { cout << "its open again"; //write size of map writefile << "the size of hash map " << stringcounts.size() << endl; //write words in map //create iterator map<string, int>::iterator = stringcounts.begin(); //iterate through map while (i != stringcounts.end()) { writefile << "the key , value : (" << i->first << "," << i->second << ")\n"; i++; } } else cout << "cant open\n"; } string lowercase(string isupper) { string toreplace = isupper; (int = 0; < toreplace.length(); i++) { if (toreplace[i] >= 65 && toreplace[i] <= 90) { toreplace[i] = tolower(toreplace[i]); } } return toreplace; }
nextstring.erase(i, i);
i doubt want. string::erase
(the 1 calling) expects position (for start erasing) , count (for how many characters erase). line erases number of characters equivalent position of character in string. so, example, if i
0, erase 0 characters. combine fact next line:
i--;
and if first character punctuation, i
stay @ 0 , loop never end. if want erase 1 character, can this:
nextstring.erase(i, 1);
but better replace whole loop , use remove/erase idiom.
auto new_end = std::remove_if(nextstring.begin(), nextstring.end(), [](char c) { // return true if c punctuation }); nextstring.erase(new_end, nextstring.end());
Comments
Post a Comment