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
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
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; }
}
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.
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;
}
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;
}
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;
}