gpt4 book ai didi

c - 关于scanf_s如何检测C中字符的问题

转载 作者:行者123 更新时间:2023-11-30 16:16:04 27 4
gpt4 key购买 nike

我试图了解这些键入的代码如何影响结果。该函数是fscanf_s

有 3 件事我不明白。

  1. 在第 11 行和第 12 行,在 &c1&c2&c3 之间,输入了某些数字。删除这些数字数字会导致 out.txt 打印空白。我不知道为什么需要之间的数字。

  2. 在第 11 行,放置了 %3c,而第 13 行的 fprintfc2 只是给出了一个空白空间。我不知道 %3c 在这里意味着什么。据我所知,该术语应该是指接受三个字符,但这里似乎并非如此。

  3. 在第 12 行,放置了 %%,导致仅更改 c4。我知道可能是 %% 停止了扫描过程,但我对此不太确定。 fscanf_s不是承认在%%之后,它必须再扫描一个%c吗?

我知道 fscanf_s 显示与 scanf_s 类似的行为,但了解它们并不能完全给我答案。

char c1 = 'a', c2 = 'b', c3 = 'c', c4 = 'd', c5 = 'e', c6 = 'g';

int i, j;
FILE* infile, * outfile;
fopen_s(&infile, "data.txt", "r");
fopen_s(&outfile, "out.txt", "w");

i = fscanf_s(infile, "%c%3c%c", &c1, 1, &c2, 1, &c3, 1); //this line 11
j = fscanf_s(infile, "%c %% %c", &c4, 1, &c5, 1, &c6, 1);//and this line 12
fprintf(outfile, "%c%c%c: (%d)\n", c1, c2, c3, i);
fprintf(outfile, "%c%c%c: (%d)\n", c4, c5, c6, j);

data.txt 打印如下:

ABCDEFGHIJKLMN

out.txt 打印如下:

A c: (1)
Deg: (1)

最佳答案

您应该介意在 CppReference 上搜索信息。 This single page给了我很多关于你在这里问的答案的信息。不过,我必须承认有些行为仍然不明显,但我希望能够帮助您更好地理解代码中发生的情况。

  1. fscanf_s is same as [fscanf], except that %c, %s, and %[ conversion specifiers each expect two arguments (the usual pointer and a value of type rsize_t indicating the size of the receiving array, which may be 1 when reading with a %c into a single char)". (source : the link above)

    好的,您已经找到了额外号码的来源。它们只是指定您将收到的字符数的数字,对于 char 必须是一个。 .

<小时/>
  • Following errors are detected at runtime and call the currently installed constraint handler function: [...] The number of characters that would be written by %c, %s, or %[, plus the terminating null character, would exceed the second (rsize_t) argument provided for each of those conversion specifiers (source : the link above)

    这意味着当使用%3c时但参数为 &c2, 1您尝试从文件中获取 3 个字符,但在 c2 中只需要一个字符...这会导致 constraint handler 处理错误函数,第 11 行中的调用应返回 EOF。我必须承认我仍然对你得到的行为有点困惑(函数调用返回 1),但 %3c 的使用肯定有问题。带参数&c2, 1 .

  • <小时/>
  • %% matches literal % (source: the link above)

    %%的用法好像很给力fscanf_s寻找% infile 中的字符。因为它没有看到任何内容,所以它只是浏览您的文件,到达 EOF并且函数结束而不修改 c5c6 .

  • 关于c - 关于scanf_s如何检测C中字符的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56835239/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com