Mark.B
Mark.B

Reputation: 83

How to check if a string contains punctuation c++

I am attempting to iterate over a string to check for punctuation. I've tried to use ispunct() but am receiving an error that there is no matching fucntion for call to ispunct. Is there a better way to implement this?

for(std::string::iterator it = oneWord.begin(); it != oneWord.end(); it++)
{
    if(ispunct(it))
    {
    }
}

Upvotes: 1

Views: 2683

Answers (2)

eesiraed
eesiraed

Reputation: 4654

it is an iterator; it points to a character in a string. You have to dereference it to get the thing it points to.

if(ispunct(static_cast<unsigned char>(*it)))

Upvotes: 4

PaulMcKenzie
PaulMcKenzie

Reputation: 35440

Is there a better way to implement this?

Use std::any_of:

#include <algorithm>
#include <cctype>
#include <iostream>

int main()
{
   std::string s = "Contains punctuation!!";
   std::string s2 = "No puncuation";
   std::cout << std::any_of(s.begin(), s.end(), ::ispunct) << '\n';
   std::cout << std::any_of(s2.begin(), s2.end(), ::ispunct) << '\n';
}

Live Example

Upvotes: 6

Related Questions