Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the isspace function in c++?

Tags:

c++

function

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.

like image 326
Robolisk Avatar asked Dec 09 '22 03:12

Robolisk


1 Answers

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.

like image 177
Seth Carnegie Avatar answered Dec 27 '22 03:12

Seth Carnegie