繁体   English   中英

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就会在输入后停止读取(如果缓冲区没有足够的空间,则不会消耗该换行符)。 因此,第一个输入的换行符留在输入 stream 中,第二次调用 fgets 会看到并停止读取输入。

当您添加getc(stdin); ,它消耗剩余的换行符,所以它可以工作。

如评论中所述,您只为a分配了n个字节,但尝试读取最多n + 1个字节。 这是未定义的行为。 因此,您需要在 malloc 调用中添加“+ 1”(就像分配b一样)。

您需要注意的另一个问题是,如果 fgets 有足够的空间(例如,您只输入“hi”而n为 10), fgets也会将换行符读入ab

另一个问题是,如果给定的输入小于n ,则循环仍会比较n字符。 这可能未定义,因为缓冲区的 rest 未初始化。

当出现不匹配时,您也可以立即break循环。 无需比较字符的 rest。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM