当我使用 scanf_s 时我得到 4,但当我使用 fgets() 时得到 1

I get 4 when I use scanf_s but 1 when I use fgets()?

本文关键字:fgets scanf      更新时间:2023-10-16
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
void main()
{
    char s[200];
    int count = 0, i;
    printf("enter the stringn");
    //scanf_s("%[^n]s", s, sizeof(s));
    fgets(s, sizeof*(s), stdin);
    for (i = 0;s[i] != '';i++)
    {
        if (s[i] == ' ')
        count++;
    }
    printf("number of words in given string are: %dn", count + 1);
    getchar();
}

fgets(s, sizeof*(s), stdin); -- 是错误的。 应该是sizeof(s)

*(s) 是字符(数组的第一个元素),而 s 是数组。因为单个字符的大小为 1,所以得到 1。

相关文章: