Program not removing punctuation correctly!

I am trying to write function that takes two string parameters- sentence and punctuation and returns the same string in lowercase and with given punctuation removed. It must be done with nested loops.

My code is as follows;

string lowerNoPunctuation(string str, string punct)
{
for(int i=0; i<str.length(); i++)
{
str[i]= tolower(str[i]);
while (ispunct(str[i]))
{
str.erase(i, 1);
str[i]= tolower(str[i]);
}
}
return str;
}

I don't have to include a main() since this is submitted through an autograder.

this is an example of the issue im having



str = "I think, I am! I think, I can! Can you?";
punct = ".,!;";

expected:
i think i am i think i can can you?

my code returns:
i think i am i think i can can you

ex2:


str = "I think, I am! I think, I can! Can you?";
punct = "., !;";

expected:
ithinkiamithinkicancanyou?

my code returns:
i think i am i think i can can you


For the first example I don't exactly understand why given that the "?" is not declared in the string my output still removes it.

For the second example I don't know how to get the blank space to be recognized as a character and how I can implement it in the code, also why it still removes "?" when again, it is not in that particular string.

Thank you for any help

ispunct is a a function built into the C/C++ standard libraries.
ispunct includes punctuation like question marks.

You'll need to write your own function that tries to find if a character you are checking is in your given punct string. You'll need to use a for loop and compare the current character you are checking to every character in your punct string -- if the character you are checking does not match any character in the punct string, it is not punctuation. If the input character is found in the punct string, it will be considered punctuation. Try to code that logic.

1
2
3
4
5
6
7
8
9
bool custom_ispunct(char c, std::string punct)
{
    bool matches = false;
    for (size_t i = 0; i < punct.length(); i++)
    {
        // fill the rest in, check the character against each character in the punct string.
    }
    return matches;
}


Also, to be safe, you should put i--; after str.erase(i, 1); because you're mutating your string within the loop itself.
Last edited on
Thank you for the help!
From the problem description -- that you need to solve the problem with nested loops -- I don't think you need your own separate, custom ispunct function. That functionality should be handled by the inner loop.

And you should only need two loops: an outer loop to walk though the characters in the string, the inner one looking to see if that char is found in the punct string (that is, doing the work of the is_punct function.) Etc.

Andy

PS Does autograder provide feedback on how well the function was coded, or just check that it returns the right results?
Last edited on
Topic archived. No new replies allowed.