fgets 没有接受两个字符串的输入
fgets wasn't taking input of two strings
我解决了问题,但仍有疑问
这是我的代码:
#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);
}
添加getc(stdin);
后问题解决了
但是有人可以告诉我它到底在做什么吗?我不知道为什么会这样!
fgets
在输入后看到换行符后停止读取(如果缓冲区没有足够的 space,则不会消耗)。因此来自第一个输入的换行符留在输入流中,第二次调用 fgets 看到并停止读取输入。
当您添加 getc(stdin);
时,它会消耗剩余的换行符,因此可以正常工作。
如评论中所述,您仅为 a
分配了 n
字节,但试图读取最多 n + 1
字节。这是未定义的行为。因此,您需要在 malloc 调用中添加“+ 1”(就像分配 b
时所做的那样)。
另一个你需要注意的问题是,如果 fgets
有足够的 space (例如,您只输入 "hi" 而 n
是 10)。
另一个问题是,如果给定的输入小于 n
,您的循环仍会比较 n
个字符。这可能是未定义的,因为其余缓冲区未初始化。
您也可以 break
在出现不匹配时立即退出循环。无需比较其余字符。
我解决了问题,但仍有疑问 这是我的代码:
#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);
}
添加getc(stdin);
后问题解决了
但是有人可以告诉我它到底在做什么吗?我不知道为什么会这样!
fgets
在输入后看到换行符后停止读取(如果缓冲区没有足够的 space,则不会消耗)。因此来自第一个输入的换行符留在输入流中,第二次调用 fgets 看到并停止读取输入。
当您添加 getc(stdin);
时,它会消耗剩余的换行符,因此可以正常工作。
如评论中所述,您仅为 a
分配了 n
字节,但试图读取最多 n + 1
字节。这是未定义的行为。因此,您需要在 malloc 调用中添加“+ 1”(就像分配 b
时所做的那样)。
另一个你需要注意的问题是,如果 fgets
有足够的 space (例如,您只输入 "hi" 而 n
是 10)。
另一个问题是,如果给定的输入小于 n
,您的循环仍会比较 n
个字符。这可能是未定义的,因为其余缓冲区未初始化。
您也可以 break
在出现不匹配时立即退出循环。无需比较其余字符。