Search code examples
c++punctuation

C++ how to remove puncuation from a string array?


In the following program showed below I attempted to remove all puncuation from a string array using ispunct

std::string fileName;
std::fstream readFile;
const int arraySize = 50000;
std::string storeFile[arraySize];

int main(int argc, char *argv[]){

for (int i = 0, len = storeFile[i].size(); i < len; i++) {  
 
if (ispunct(storeFile[i])){//check whether parsing character is punctuation or not
          
storeFile[i].erase(std::remove_if(storeFile[i].begin(), 
                                  storeFile[i].end(),
                                  ::ispunct), storeFile[i].end());
    
            }     
        }
}

However I recieve the following error on for ispunct(storeFile[i]

function "ispunct" cannot be called with the given argument list -- argument types are: (std::string)

Ive used ispunct before for std::string but not a std::string array[]. How can I remove puncuation and white space from a string array? Thankyou

 for (int i = 0; i < arraySize; i++)
    {
        while (readFile >> storeFile[i])
        {
            std::transform(storeFile[i].begin(), storeFile[i].end(), storeFile[i].begin(), ::tolower);

            for (auto &s : storeFile)
            {
                s.erase(std::remove_if(s.begin(), s.end(), ::ispunct), s.end());
                s.erase(std::remove_if(s.begin(), s.end(), ::isspace), s.end());
            }


             }
        }
        

Solution

  • ispunct takes 1 character as input, not an entire string.

    But you don't need to check the string before removing the punctuation. Something simple like this will work:

        for (auto& s : storeFile) {
            s.erase(std::remove_if(s.begin(), s.end(), ::ispunct), s.end());
        }
    

    Live demo

    ==EDIT==

    You have a fixed array of 50000 strings. If the input file contains N strings, you'll print that followed by 50000-N blank lines. It's probably not what you want. Use std::vector<std::string> instead.

        std::string s;
        std::vector<std::string> storeFile;
        while (readFile >> s) {
            std::transform(s.begin(), s.end(), s.begin(), ::tolower);
            s.erase(std::remove_if(s.begin(), s.end(), ::ispunct), s.end());
            s.erase(std::remove_if(s.begin(), s.end(), ::isspace), s.end());
            storeFile.push_back(std::move(s));
        }