如何检查scanf返回的字符串是否为null [英] How to check if a string returned by scanf is null
问题描述
我正在使用 scanf()从用户读取输入字符串.
我要检查此字符串是否为NULL(\ 0).
I want to check if this string is NULL (\0) or not.
这是我的代码:
#include<stdio.h>
char *argument; // argument for mycat
scanf("%s", &argument);
if(fork()==0) // at child
{
printf("Child process: about to execute \"mycat %s\"\n", &argument);
fflush(stdout);
if(strcmp(argument, "") == 0) // <-- Here is the problem
{
execlp("mycat", "mycat", &argument, NULL); // execute child process
}
execlp("mycat","mycat", NULL);
}
我正在Red Hat 6.1上使用g ++编译器进行编译
I'm compiling with g++ compiler on Red Hat 6.1
问题是我无法为 if
语句甚至不能与一起使用
. argument
取消引用.> strlen()
The problem is that I'm not able to dereference argument
either for the if
statement or even for use with strlen()
.
推荐答案
NULL
和 \ 0
并不是同一个东西,尽管它们的求和结果均为零. NULL
是零指针,即我们用于null指针的指针. \ 0
是ASCII码为零的字符,否则称为 NUL
(一个'L'),即是一个值为0的 char
.
NULL
and \0
are not the same thing, though they both evaluate to zero. NULL
is a pointer zero, i.e. it's what we use for a null pointer. \0
is the character with ASCII number zero, otherwise known as NUL
(one 'L'), i.e. is a char
with value 0.
char *
为 NULL
(即内存中根本没有字符串)或字符串为空(即仅包含一个 char
,即 \ 0
,否则称为 NUL
).
There is an important difference between a char *
being NULL
(i.e. there not being a string in memory at all), or the string being empty (i.e. only containing one char
which is \0
otherwise known as NUL
).
要测试第一个:
if (!string)
或者如果您想更详细些:
or if you like to be more verbose:
if (string == NULL)
要测试第二个:
if (!string[0])
或者如果您想更详细些:
or if you like to be more verbose:
if (string[0] == 0)
很明显,如果您需要同时测试两者,请先测试第一个,然后再测试第二个,因为如果 string
为 NULL
,则第二个将取消引用空指针.
Obviously if you need to test for both, test for the first then the second, as the second would dereference a null pointer if string
was NULL
.
这篇关于如何检查scanf返回的字符串是否为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!