-1

Can anybody help me? In the code i have instead of erasing the punctuation as shown, i need to strip it out to be re-used later on when the word that precedes it has been expanded from its abbreviated form. Any help would be greatly appreciated. N.B This is only one function of the code, to display the vectors and open the infile etc... have been placed in separate functions.

void readText2(ifstream &infile, vector <string> &textFile2 ) 
{
    while( !infile.eof() )
    {
        string fileWord;
        infile >> fileWord;
        for (size_t i=0; i !=fileWord.length(); i++)
        {
            fileWord[i]=toupper(fileWord[i]);
        }

        for (size_t i=0; i < fileWord.length(); i++)
        {
            if (ispunct (fileWord[i]))
            {
                fileWord.erase(i); 
            }
        }
        textFile2.push_back(fileWord);
    }
    infile.close();
}
Potatoswatter
  • 134,909
  • 25
  • 265
  • 421
maccame
  • 45
  • 1
  • 5

1 Answers1

0

I'd suggest traversing the string end-to-begin (to preserve the correct index numbers), and inside the loop store the index+punctuation charactar in an std::map<size_t,char>

Your function hacked, with comments where stuff changed:

// changed return type
vector<map<size_t,char>> readText2(ifstream &infile, vector <string> &textFile2 ) 
{
    vector<map<size_t,char>> vPunct;    // added

    while( !infile.eof() )
    {
        string fileWord;
        infile >> fileWord;
        for (size_t i=0; i !=fileWord.length(); i++)
        {
            fileWord[i]=toupper(fileWord[i]);
        }

        map<size_t,char> mPunct;        // construct a map
                                        // map stays empty if no punctuation is found

        for (size_t i=fileWord.length()-1; i>=0 ; i--)    // reversed loop
        {
            if (ispunct (fileWord[i]))
            {
                // store index + punctuation char
                mPunct.insert(pair<size_t,char>(i,fileWord[i]));     
                fileWord.erase(i); 
            }
        }
        textFile2.push_back(fileWord);      
        vPunct.push_back(mPunct);      // add map to vector
    }
    infile.close();
    return vPunct;   // return vector
}

The punctuation is now stored in a second vector, which the function returns. For example: a string at textFile[20] has its punctuation stored in vPunct[20].

It would be more reliable to store the punctuation together with the string in one vector<pair<string,map<size_t,char>>>, but that would alter the external behavior of the function, and I dont know if that is desireable for you.

Erik van Velzen
  • 6,211
  • 3
  • 23
  • 23