I\'m writing a very small program in C that needs to check if a certain string is empty. For the sake of this question, I\'ve simplified my code:
#include
It is very simple. check for string empty condition in while condition.
You can use strlen function to check for the string length.
#include<stdio.h>
#include <string.h>
int main()
{
char url[63] = {'\0'};
do
{
printf("Enter a URL: ");
scanf("%s", url);
printf("%s", url);
} while (strlen(url)<=0);
return(0);
}
check first character is '\0'
#include <stdio.h>
#include <string.h>
int main()
{
char url[63] = {'\0'};
do
{
printf("Enter a URL: ");
scanf("%s", url);
printf("%s", url);
} while (url[0]=='\0');
return(0);
}
For your reference:
C arrays:
https://www.javatpoint.com/c-array
https://scholarsoul.com/arrays-in-c/
C strings:
https://www.programiz.com/c-programming/c-strings
https://scholarsoul.com/string-in-c/
https://en.wikipedia.org/wiki/C_string_handling
With strtok(), it can be done in just one line: "if (strtok(s," \t")==NULL)". For example:
#include <stdio.h>
#include <string.h>
int is_whitespace(char *s) {
if (strtok(s," \t")==NULL) {
return 1;
} else {
return 0;
}
}
void demo(void) {
char s1[128];
char s2[128];
strcpy(s1," abc \t ");
strcpy(s2," \t ");
printf("s1 = \"%s\"\n", s1);
printf("s2 = \"%s\"\n", s2);
printf("is_whitespace(s1)=%d\n",is_whitespace(s1));
printf("is_whitespace(s2)=%d\n",is_whitespace(s2));
}
int main() {
char url[63] = {'\0'};
do {
printf("Enter a URL: ");
scanf("%s", url);
printf("url='%s'\n", url);
} while (is_whitespace(url));
return 0;
}
If you want to check if a string is empty:
if (str[0] == '\0')
{
// your code here
}
You can check the return value from scanf
. This code will just sit there until it receives a string.
int a;
do {
// other code
a = scanf("%s", url);
} while (a <= 0);
I've written down this macro
#define IS_EMPTY_STR(X) ( (1 / (sizeof(X[0]) == 1))/*type check*/ && !(X[0])/*content check*/)
so it would be
while (! IS_EMPTY_STR(url));
The benefit in this macro it that it's type-safe. You'll get a compilation error if put in something other than a pointer to char.
First replace the scanf()
with fgets()
...
do {
if (!fgets(url, sizeof url, stdin)) /* error */;
/* ... */
} while (*url != '\n');