使用scanf函数与普通防爆pressions [英] Use scanf with Regular Expressions

查看:183
本文介绍了使用scanf函数与普通防爆pressions的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图在scanf函数使用常规的前pressions,为了读取最大n个字符的字符串,并丢弃任何东西,直到换行字符。任何空格应被视为常规字符,因此包括在字符串中被读取。
我研究对固定防爆pressions维基百科文章,但我不能让scanf的正常工作。下面是一些code我试过:

I've been trying to use regular expressions on scanf, in order to read a string of maximum n characters and discard anything else until the New Line Character. Any spaces should be treated as regular characters, thus included in the string to be read. I've studied a Wikipedia article about Regular Expressions, yet I can't get scanf to work properly. Here is some code I've tried:

scanf("[ ]*%ns[ ]*[\n]", string);

[]应该去实际空格字符,*假定为是指一种或多种,​​n为要读取的字符数和字符串是使用malloc分配的指针。
我尝试了好几种不同的组合;然而,我倾向于只得到一个句子读的第一个字(在空格字符停止)。此外,*似乎丢弃字符而不是意为零个或多个...

[ ] is supposed to go for the actual space character, * is supposed to mean one or more, n is the number of characters to read and string is a pointer allocated with malloc. I have tried several different combinations; however I tend to get only the first word of a sentence read (stops at space character). Furthermore, * seems to discard a character instead of meaning "zero or more"...

可能有人详细讲解前pressions如何定期由scanf函数PTED间$ P $?更重要的是,它是有效地使用GETC重复呢?

Could anybody explain in detail how regular expressions are interpreted by scanf? What is more, is it efficient to use getc repetitively instead?

在此先感谢:D

推荐答案

简短的回答: scanf函数不逐字处理正前pressions讲

The short answer: scanf does not handle regular expressions literally speaking.

如果你想在C使用常规的前pressions,你可以使用正则表达式POSIX库。请参见下面的问题一个基本的例子对这个库的使用:普通EX $ P $用C pssions:例子

If you want to use regular expressions in C, you could use the regex POSIX library. See the following question for a basic example on this library usage : Regular expressions in C: examples?

现在,如果你想这样做的 scanf函数的方式,你可以尝试像

Now if you want to do it the scanf way you could try something like

scanf("%*[ ]%ns%*[ ]\n",str);

由字符的最大数量%NS 替换 N 从输入流中读取。
%* [] 部分询问忽略任何空格。你可以替换 * 通过一个具体的数字忽略字符的precise号。你可以花括号之间添加其他字符忽略的不仅仅是空间了。

Replace the n in %ns by the maximal number of characters to read from input stream. The %*[ ] part asks to ignore any spaces. You could replace the * by a specific number to ignore a precise number of characters. You could add other characters between braces to ignore more than just spaces.

不知道上面的scanf函数将工作作为空间也与%S 指令匹配。

我肯定会使用与fgets 电话去,然后用类似下面的修边周围的空格:<一href=\"http://stackoverflow.com/questions/122616/how-do-i-trim-leading-trailing-whitespace-in-a-standard-way\">How我修剪引导/标准方式尾随空白?

Not sure if the above scanf would work as spaces are also matched with the %s directive.
I would definitely go with a fgets call, then triming the surrounding whitespaces with something like the following: How do I trim leading/trailing whitespace in a standard way?

这篇关于使用scanf函数与普通防爆pressions的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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