[英]fgets wasn't taking input of two strings
I solved the question but still have a doubt Here's my code:我解决了这个问题,但仍有疑问这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argv, char *argc[])
{
if (argv != 2)
{
printf("Invalid Input, Please enter the length of the strings you wish to compare\n");
return 1;
}
int n = atoi(argc[1]);
char *a = malloc((sizeof(char) * n));
printf("Enter the first string - ");
fgets(a, n + 1, stdin);
getc(stdin);
char *b = malloc((sizeof(char) * n) + 1);
printf("Enter second string - ");
fgets(b, n + 1, stdin);
int d = 0;
for (int i = 0; i < n; i++)
{
if (*(a + i) != *(b + i))
{
d++;
}
}
if (d == 0)
{
printf("The two strings are identical\n");
}
else
{
printf("The two strings are not identical\n");
}
free(a);
free(b);
}
My problem was solved after i added getc(stdin);
添加
getc(stdin);
But can someone please tell me what exactly it is doing?但是有人可以告诉我它到底在做什么吗? I don't know why it works!
我不知道为什么它有效!
fgets
stops reading after input once it sees a newline (which isn't consumed if the buffer doesn't have enough space).一旦看到换行符,
fgets
就会在输入后停止读取(如果缓冲区没有足够的空间,则不会消耗该换行符)。 So newline from first input is left in the input stream, which the second call to fgets sees and stops reading input.因此,第一个输入的换行符留在输入 stream 中,第二次调用 fgets 会看到并停止读取输入。
When you add getc(stdin);
当您添加
getc(stdin);
, it consumes the leftover newline char, so it works. ,它消耗剩余的换行符,所以它可以工作。
As noted in comments, you're allocating only n
bytes for a
but attempting to read upto n + 1
bytes.如评论中所述,您只为
a
分配了n
个字节,但尝试读取最多n + 1
个字节。 This is undefined behaviour.这是未定义的行为。 So you'd need add " + 1" to the malloc call (like you do for the allocation of
b
).因此,您需要在 malloc 调用中添加“+ 1”(就像分配
b
一样)。
Another problem that you need to be aware of is, fgets
will read the newline character too into a
and b
if the they have enough space (eg you enter just "hi" and n
is 10).您需要注意的另一个问题是,如果 fgets 有足够的空间(例如,您只输入“hi”而
n
为 10), fgets
也会将换行符读入a
和b
。
And another problem is that if input given is less than n
, you loop still compares n
chars.另一个问题是,如果给定的输入小于
n
,则循环仍会比较n
字符。 This could be undefined as the rest of buffers are uninitialized.这可能未定义,因为缓冲区的 rest 未初始化。
You can also break
out of the loop immediately when there's a mismatch.当出现不匹配时,您也可以立即
break
循环。 No need compare the rest of the chars.无需比较字符的 rest。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.