I'm trying to figure out how to use this function. I found it on the web and apparently it checks if you have a space in your string. So it's not working out for me. I've figured out that I'm not even getting into the if statement that I need to.
for (i=0;i < marks.length();i++)
{
if (isdigit(marks[i]))
{
floatMARK = 1;
}
else
{
charMARK = 1;
}
}
if (floatMARK == 1)
{
printf("were in.");
for (i=0;i < marks.length();i++)
{
if (isspace(marks[i]))
{
multiMARK = 1;
printf("WE HAVE A SPACE!!");
}
}
}
Anyone know what I'm doing wrong? If you need me to clarify anything, let me know.
All that is very unnecessary to just test if a string has a space in it. This is all you need:
#include <ctype.h>
bool hasspace = std::find_if(str.begin(), str.end(), ::isspace) != str.end();
:: is the scope resolution operator specifying that isspace is a global function, not the similarly-named std::isspace, and find_if is a function inside std::. If you use using namespace std; then you don't need std:: but you do still need the plain ::.
The find_if function takes an iterator to the beginning of the string, an iterator to the end of the string, and a function that takes an argument and returns some value convertible to a bool. find_if iterates from the first iterator to the second iterator, passing each value of the current item to the function you gave it, and if the function returns true, find_if returns the iterator that caused the function to return true. If find_if goes through to the end and the function never returns true, then it returns an iterator to the end of the range, which in this case is str.end().
That means that if find_if returns str.end(), it got to the end of the string without isspace returning true, which means there was no space characters in the string. Therefore, you can test the result of find_if against str.end(); If they are unequal (!=), that means there was a space in the string, and hasspace is true. Else, hasspace is false.
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