[英]fgets() reads fewer characters than expected
I created function that takes in a char pointer. 我创建了一个带有char指针的函数。 I first get the string value from fgets, the input i'm entering is "rwx".
我首先从fgets获取字符串值,我输入的输入是“ rwx”。 When I enter that value, the strlen of it says it's length is 2 and when I look at the first index of the char array, it returns
rw
instead of r
. 当我输入该值时,其strlen表示其长度为2,并且当我查看char数组的第一个索引时,它返回
rw
而不是r
。 May I ask where abouts am I going wrong for iterating through the string? 我可以问一下迭代字符串在哪里出错了吗?
What I've tried: 我试过的
int main()
{
char access[3];
while (ValidateAccess(access))
{
printf("Please enter your access\n");
fgets (access, 3, stdin);
}
return 0;
}
int ValidateAccess(char * access)
{
int length = strlen(access);
int r = 0,w = 0,x = 0,i;
printf("this is the length %d\n", length);
if (length == 0)
return 1;
for(i = 0; i < length; i++)
{
printf("this is the character: %s", &access[i]);
if (strcmp(&access[i], "r") == 0)
r++;
else if (strcmp(&access[i], "w") == 0)
w++;
else if (strcmp(&access[i], "x") == 0)
x++;
}
if (r <=1 && w <= 1 && x <= 1 )
return 0;
else
return 1;
}
when the program is ran this is the output 当程序运行时,这是输出
"this is the length 0"
Please enter your access
rwx
this is the length 2
this is the character: rw
man fgets
is a very useful reading. man fgets
是一本非常有用的书。 Let me quote: "fgets() reads in at most one less than size characters from stream..." 让我引用一下:“ fgets()读取的流最多不超过流中字符的大小...”
The strings in C are expected to be terminated with \\0
(zero byte). C中的字符串应以
\\0
(零字节)结尾。 When you define access
as an array of 3 elements, it has a room for a string of length 2 -- two characters plus terminating zero byte . 当您将
access
定义为3个元素的数组时,它有一个空间来容纳长度为2的字符串-两个字符加零字节结尾 。 When you call fgets
saying that you have the space for 3 bytes, it reads two characters, puts them in the first two bytes, and puts terminating zero in the third byte. 当您调用
fgets
表示您有3个字节的空间时,它将读取两个字符,将它们放在前两个字节中,并在第三个字节中以零结尾。
Define access
a having 4 bytes, and pass 4 to fgets
. 定义具有4个字节的
access
a,并将4传递给fgets
。
Additionally, you are printing string not a char , so it prints everything to the terminating zero byte (that's where rw
you see comes from). 另外,您要打印的字符串不是char ,因此它将所有内容打印到终止的零字节(这是您看到的
rw
来源)。 If you want to print a single character, use %c
in format string, not %s
(and you should pass a character, not a pointer then). 如果要打印单个字符,请在格式字符串中使用
%c
,而不要在%s
(然后应传递一个字符,而不是指针)。
Try the following program and make sure you understand the output. 尝试以下程序,并确保您了解输出。
#include <stdio.h>
int main() {
char *foo = "barbaz";
printf("%c\n", foo[2]);
printf("%s\n", foo + 2);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.