views:

60

answers:

5

Is there an easy way to check if a line is empty. So i want to check if it contains any white space such as \r\n\t and spaces.

Thanks

A: 

Given a char *x=" "; here is what I can suggest:

bool onlyspaces = true;
for(char *y = x; *y != '\0'; ++y)
{
    if(*y != '\n') if(*y != '\t') if(*y != '\r') if(*y != ' ') { onlyspaces = false; break; }
}
Benoit
+5  A: 

You can use the isspace function in a loop to check if all characters are whitespace:

int is_empty(const char *s) {
  while (*s != '\0') {
    if (!isspace(*s))
      return 0;
    s++;
  }
  return 1;
}

This function will return 0 if any character is not whitespace (i.e. line is not empty), or 1 otherwise.

casablanca
the argument to `isspace` should be cast to `unsigned char` (the is* functions "do not like" negative input and `char` may be signed): `isspace((unsigned char)*s)`
pmg
that will work. Thanks!
Matt
A: 

If a string s consists only of white space characters then strspn(s, " \r\n\t") will return the length of the string. Therefore a simple way to check is strspn(s, " \r\n\t") == strlen(s) but it will traverse the string twice. You can also write a simple function that would look at the string only once:

bool isempty(const char *s)
{
  while (*s) {
    if (!isspace(s)) return false;
    s++;
  }
  return true;
}
Geoff Reedy
A: 

Consider the following example:

#include <iostream>
#include <ctype.h>

bool is_blank(const char* c)
{
    while (*c)
    {
       if (!isspace(*c))
           return false;
       c++;
    }
    return false;
}

int main ()
{
  char name[256];

  std::cout << "Enter your name: ";
  std::cin.getline (name,256);
  if (is_blank(name))
       std::cout << "No name was given." << std:.endl;


  return 0;
}
Rizo
`str`, `*c`, `c` which is it? :-)
pmg
@pmg: Only `str` is wrong. `*c` is the value of `c`, so it's ok! But thank you!
Rizo
A: 

I won't check for '\0' since '\0' is not space and the loop will end there.

int is_empty(const char *s) {
  while ( isspace( (unsigned char)*s) )
          s++;
  return *s == '\0' ? 1 : 0;
}
Nyan