%[^\n] 在 scanf() 格式字符串中是什么意思 [英] What does %[^\n] mean in a scanf() format string

查看:80
本文介绍了%[^\n] 在 scanf() 格式字符串中是什么意思的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I saw on this website that this: fscanf(fin, "%[^\n]", &p); could be used for reading from my input file(fin) into that char type pointer(*p) all the characters until the first enter hit. At some inputs it works properly, but at others it doesn't.

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

This is the input I should process and I cannot:

(((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;
}

推荐答案

%[ 表示法引入了一种叫做扫描集"的东西,它有点像正则表达式(但没有那么强大).

The %[ notation introduces something called a "scanset" which is somewhat like a regular expression (but not as powerful).

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

In your specific example it means the format specifier instructs scanf to keep scanning characters that match anything except an \n (encountering a non-matching character will terminate the scan).

来自 C11 标准:

转换说明符包括所有后续字符格式字符串,直到并包括匹配的右括号 (]).这括号之间的字符(扫描列表)组成扫描集,除非左括号后面的字符是抑扬符号 (^),in在这种情况下,扫描集包含所有未出现在抑扬符和右括号之间的扫描列表.

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 发现您代码的真正问题是:

The real problem with your code, spotted by Jonathan Leffler is this:

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

删除 & 因为您想传递 p,而不是p 的地址".

Drop the & since you want to pass p, not "the address of p".

这篇关于%[^\n] 在 scanf() 格式字符串中是什么意思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆