Since C-style strings are always terminated with the null character (\0), you can check whether the string is empty by writing
do {
...
} while (url[0] != '\0');
Alternatively, you could use the strcmp function, which is overkill but might be easier to read:
do {
...
} while (strcmp(url, ""));
Note that strcmp returns a nonzero value if the strings are different and 0 if they're the same, so this loop continues to loop until the string is empty.
Hope this helps!
Answer from templatetypedef on Stack OverflowSince C-style strings are always terminated with the null character (\0), you can check whether the string is empty by writing
do {
...
} while (url[0] != '\0');
Alternatively, you could use the strcmp function, which is overkill but might be easier to read:
do {
...
} while (strcmp(url, ""));
Note that strcmp returns a nonzero value if the strings are different and 0 if they're the same, so this loop continues to loop until the string is empty.
Hope this helps!
If you want to check if a string is empty:
if (str[0] == '\0')
{
// your code here
}
What is the best way to check for a blank string?
How to get the address of string ""
string variable unexpectedly becomes an empty string
Should we optimize or deprecate `string.Empty` in C#?
Videos
Perhaps this is trivial, but I got to wondering what is considered the "best" way to check for a blank string. I was specifically thinking of Javascript, although this could be applied to a number of languages. (Any C-style language) I thought up a couple solutions...
if (foo == "") ...
if (foo.length() == 0) ...
Not included in Javascript, but in languages that have it:
if (foo.isEmpty()) ...
Which of these is generally considered the most elegant/readable? Is it the single-purpose function, or a general-purpose function with a comparison? Or does it just not matter?
For some reason, the name variable becomes empty even though I gave it an input.
Code:
#include <stdio.h>
int main(){
char name[16];
short unsigned int age;
printf("What is your name? ");
scanf("%s", &name);
printf("How old are you? ");
scanf("%u", &age);
printf("Hello, %s.\n", name);
printf("You are %u years old\n", age);
return 0;
}Terminal:
What is your name? Momus How old are you? 99 Hello, . You are 99 years old
I seems that the value for name was changed in the part somewhere in the part that prints "How old are you? " and the scanf() for the value of age because it works when I do this.
Code:
#include <stdio.h>
int main(){
char name[25];
short unsigned int age;
printf("What is your name? ");
scanf("%s", &name);
printf("Hello, %s.\n", name);
printf("How old are you? ");
scanf("%u", &age);
printf("You are %u years old\n", age);
return 0;
}Terminal:
What is your name? Momus Hello, Momus. How old are you? 99 You are 99 years old
Does anyone know what happened? How do I make it so that the first one will show the input? Thanks!