gpt4 book ai didi

c++ - %[^\n] 在 scanf() 格式字符串中是什么意思

转载 作者:行者123 更新时间:2023-11-30 00:49:57 26 4
gpt4 key购买 nike

我在这个网站上看到:fscanf(fin, "%[^\n]", &p); 可用于读取我的输入文件(fin) 到 char 类型指针 (*p) 中的所有字符,直到第一个输入命中。在某些输入下它可以正常工作,但在其他输入下则不能。

这是我应该处理的输入,但我不能:

(((zahar 100 ou 3) 5 unt 100 nuca 200) 4 (lapte 200 cacao 50 zahar 100)3)20

这是我的全部代码:

#include <string.h>
#include <stdio.h>
FILE *fin, *fout;
int main()
{
fin = fopen("reteta.in", "r");
fout = fopen("reteta.out", "w");
char *p;
p = new char[1001]();
fscanf(fin, "%[^\n]", &p);
fprintf(fout, "%s", &p);
return 0;
}

最佳答案

%[ 表示法引入了一种称为“扫描集”的东西,它有点像正则表达式(但没有那么强大)。

在您的具体示例中,这意味着格式说明符指示 scanf 继续扫描匹配除 \n 之外的任何字符(遇到不匹配的字符将终止扫描).

来自 C11 标准:

The conversion specifier includes all subsequent characters in the format string, up to and including the matching right bracket (]). The characters between the brackets (the scanlist) compose the scanset, unless the character after the left bracket is a circumflex (^), in which case the scanset contains all characters that do not appear in the scanlist between the circumflex and the right bracket.


即使将它与正则表达式进行比较也是对它的延伸:标准只是简单地说:“匹配一组预期字符中的非空字符序列”。


Jonathan Leffler 发现了您的代码的真正问题是:

fscanf(fin, "%[^\n]", &p);
^

删除 & 因为你想传递 p,而不是“p 的地址”。

关于c++ - %[^\n] 在 scanf() 格式字符串中是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26597624/

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