如何检查是否C字符串是空的 [英] How to check if C string is empty
问题描述
我在C语言编写一个非常小的程序,需要检查如果某个字符串是空的。对于这个问题的缘故,我已经简化我的code:
的#include<&stdio.h中GT;
#包括LT&;串GT;诠释主(){
字符的URL [63] = {'\\ 0'};
做{
的printf(请输入网址:);
scanf函数(%S,URL);
的printf(%S,URL);}而(/ *我应该摆在这里* /?);返回(0);
}
我希望程序停止循环,如果用户只是presses不输入任何输入。
感谢。
编辑:
我这里有一个小问题。当我点击,而无需输入任何内容到终端输入,光标刚刚跳下到下一行。有没有什么,只是已经提交什么,而不必将它移动到下一行?
编辑:
我发现,添加 [^ \\ n] 在scanf中让我输入任何内容,仍然有它提交。然而,当我在做什么类型,它运行一个更多的时间,然后自行退出循环。下面是更新code:
INT的main(){
字符的URL [63] = {'\\ 0'};
做{
的printf(请输入网址:);
scanf函数(%[^ \\ n]的,URL);
}而(URL [0] ='\\ 0'!);返回(0);
}
由于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!
这篇关于如何检查是否C字符串是空的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!