Reputation: 31
I am working with a vector and am trying to populate the vector with a list of words from a txt file on the condition that the word has no punctuation. I am looking at each line as a string and am trying to find a good way to test if the string has punctuation in it.
I have something like this working for all the apostrophes in the string but need to generalize this to all punctuation. If the line has no apostrophes, then continue to the rest of the code.
if ((find(line.begin(), line.end(), '\'')) == line.end())
I am fairly new and any help would be appreciated. I looked at possibly using the ispunct() function but couldn't figure out how to implement that into this.
Upvotes: 0
Views: 2388
Reputation: 12928
You can use std::any_of and std::ispunct.
When using something like std::any_of
or std::find_if
the easiest thing to do is to pass it a lambda.
For your case it would look like
#include <iostream>
#include <algorithm>
#include <cctype>
int main() {
std::string str = "fdsfd/jl";
if (std::any_of(str.begin(), str.end(), [](char c){ return std::ispunct(c); } ))
std::cout << "PUNCT!";
return 0;
}
Our lambda [](char c){ return std::ispunct(c); }
will take one char and return the result of std::ispunct
on that char.
Upvotes: 1