views:

109

answers:

5

I have a GtkEntry where the user has to enter an IP number or a hostname. When the button is pressed what the user typed into the entry is added to a char. How can I programmatically check if this char contains spaces, the newline character or the tab character? I don't need to remove them, just to know if they exist. Thanks in advance!

+7  A: 

Take a look at character classification routines: man isspace.

Nikolai N Fetissov
I doesn't work though if the first character of the char is a "space".
Levo
@Levo, `char` is an 8-bit integer usually holding an ASCII code for a single letter. `char*` is a *pointer* to *array of* these and is used as a "string" in C. The classification functions mentioned work on *individual* characters, not the strings.
Nikolai N Fetissov
+4  A: 

Create a char array containing the characters of interest. Then use strchr() to search for the presence of the char in the string.

char charSet[] = { ' ', '\n', '\t', 0 };
char c;

// code that puts a character in c

if (strchr(charSet, c) != NULL)
{
    // it is one of the set
}
Amardeep
The user input was not a single character but a string, such as "IP number or a hostname".
PauliL
@PauliL: The user input is a string. However, the question was worded to ask about the char generated with each keypress.
Amardeep
A: 

Let us suppose you mean that what is typed into the GtkEntry is added to an array of char (a string, in C terminology, provided that it is null terminated). Then to check if that array of char contains at least one or more of "space" characters (according to the locale, so we use isspace),

char *array;
int i;
//..
bool contains_space = false;
for(i = 0; i < strlen(array); i++) {
  if ( isspace(array[i]) ) {
    contains_space = true;
    break;
  }
}
// return contains_space

which can be turned into a function for example.

ShinTakezou
A: 

You might consider a function such as the following which counts the number of whitespace characters in the given string giving a positive integer is any are found (i.e. TRUE), zero if none are found (i.e. FALSE) and -1 on error.

#include <ctype.h>
static int
ws_count(char *s)
{
    int n = -1;
    if (s != NULL) {
        char *p;
        for (n = 0, p = s; *p != '\0'; p++) {
            if (isspace(*p)) {
                n++;
            }
        }
    }
    return n;
}
bjg
+1  A: 

The function you are looking for is strpbrk().

#include <stdio.h>
#include <string.h>

int check_whitespace (char *str)
{
  char key[] = { ' ', '\n', '\t', 0 };
  return strpbrk (str, key);
}
PauliL