I'm trying to remove all punctuation characters from a std::string in C++. My current code:
string str_in;
string::size_type i, j;
cout << "please input string with punctuation character..." << endl;
cin >> str_in;
for (i = 0, j = 0; i != str_in.size(); ++i)
if (!ispunct(str_in[i]))
str_in[j++] = str_in[i];
str_in[j] = '\0';
cout << str_in << endl;
Is str_in[j] = '\0'; wrong?
If you want to truncate str_in to the first j characters, you can say str_in.resize(j).
If you want to use the standard library you could apply the erase-remove idiom like this:
#include <algorithm>
#include <iostream>
#include <string>
int main()
{
std::string str_in;
std::getline(std::cin, str_in);
// Here is where the magic happens...
str_in.erase(std::remove_if(str_in.begin(), str_in.end(), ::ispunct), str_in.end());
std::cout << str_in << '\n';
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With