更新时间:2022-10-23 08:10:13
由于C风格的字符串总是以空字符( \\ 0
)终止,您可以检查该字符串是否为空写
{做
...
}而(URL [0] ='\\ 0'!);
另外,你可以使用 STRCMP
功能,这是矫枉过正,但可能更容易阅读:
{做
...
}而(STRCMP(URL,));
注意 STRCMP
返回一个非零值,如果字符串是不同的0,如果它们是相同的,所以这个循环不断循环,直到该字符串不为空。
希望这有助于!
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 <stdio.h>
#include <string>
int main() {
char url[63] = {'\0'};
do {
printf("Enter a URL: ");
scanf("%s", url);
printf("%s", url);
} while (/*what should I put in here?*/);
return(0);
}
I want the program to stop looping if the user just presses enter without entering anything.
Thanks.
EDIT:
I've got a small problem here. When I click enter without entering anything into the terminal, the cursor just jumps down to the next line. Is there any to just have it submit nothing instead of having it move to the next line?
EDIT:
I've found that adding [^\n] in scanf allows me to enter nothing and still have it submit. However, when I do type something in, it runs one more time and then quits the loop by itself. Here's the updated code:
int main() {
char url[63] = {'\0'};
do {
printf("Enter a URL: ");
scanf("%[^\n]s", url);
} while (url[0] != '\0');
return(0);
}
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 nonempty.
Hope this helps!