为什么代码在 c 中以如此奇怪的顺序执行?
Why code is being executed in such strange sequence in c?
int is_valid(char *input)
{
int i;
for (i = 0;; i++)
{
// Check for null terminator
if ( ! input[i])
{
printf("stop executing is_valid()");
return 0;
}
// Will be executed for null terminator... o_O
printf("%c isdigit: %d\n", input[i], isdigit(input[i]));
}
return 1;
}
int main()
{
char input[80];
fgets(input, sizeof(input), stdin);
is_valid(input);
return 0;
}
输出:
1 isdigit: 1
0 isdigit: 1
1 isdigit: 1
isdigit: 0 // Why is that here? null terminator after return?!
stop executing is_valid()invalid input!
为什么在 return 之前通过 isdigit
处理空终止符?而且..好的,为什么在它之后执行条件?
Why null terminator is processed via isdigit
before return?
不是。它对 fgets
读取的 '\n'
个字符执行。
C11-§7.21.7.2
The fgets
function reads at most one less than the number of characters specified by n
from the stream
pointed to by stream into the array pointed to by s
. No additional characters are read after a new-line character (which is retained) or after end-of-file. A null character is written immediately after the last character read into the array.
为输入
101
里面有 5
个字符
101\n[=11=]
\n
当然不是数字。
您也需要为 \n
添加条件
if (input[i] == '[=12=]' || input[i] == '\n')
{
printf("stop executing is_valid()");
return 0;
}
使用scanf("%d",&char[i]
) 获取输入。由于 fgets
也接受换行符,这就是您获得的额外输出,fgets
.
对 "\n"
的检查
int is_valid(char *input)
{
int i;
for (i = 0;; i++)
{
// Check for null terminator
if ( ! input[i])
{
printf("stop executing is_valid()");
return 0;
}
// Will be executed for null terminator... o_O
printf("%c isdigit: %d\n", input[i], isdigit(input[i]));
}
return 1;
}
int main()
{
char input[80];
fgets(input, sizeof(input), stdin);
is_valid(input);
return 0;
}
输出:
1 isdigit: 1
0 isdigit: 1
1 isdigit: 1
isdigit: 0 // Why is that here? null terminator after return?!
stop executing is_valid()invalid input!
为什么在 return 之前通过 isdigit
处理空终止符?而且..好的,为什么在它之后执行条件?
Why null terminator is processed via
isdigit
before return?
不是。它对 fgets
读取的 '\n'
个字符执行。
C11-§7.21.7.2
The
fgets
function reads at most one less than the number of characters specified byn
from thestream
pointed to by stream into the array pointed to bys
. No additional characters are read after a new-line character (which is retained) or after end-of-file. A null character is written immediately after the last character read into the array.
为输入
101
里面有 5
个字符
101\n[=11=]
\n
当然不是数字。
您也需要为 \n
添加条件
if (input[i] == '[=12=]' || input[i] == '\n')
{
printf("stop executing is_valid()");
return 0;
}
使用scanf("%d",&char[i]
) 获取输入。由于 fgets
也接受换行符,这就是您获得的额外输出,fgets
.
"\n"
的检查