简体   繁体   English

是否可以在C中使用scanf + regex获得空行?

[英]Is it possible to get empty line with scanf + regex in c?

I know that fgets is more appropriate for this, but would it be possible to use scanf to read a line that has only \\n (maybe by using a regex expression?) ? 我知道fgets更适合此操作,但是是否可以使用scanf读取仅具有\\n (也许使用正则表达式?)?

EDIT: the formqt suggester by @dasblinkenlight works to get the \\n, however, it has undesirable side effects. 编辑:@dasblinkenlight的formqt建议程序可用来获取\\ n,但是,它具有不良的副作用。 For example : 例如 :

#include <stdio.h>

int main(){
 char c[80];
 for (int n = 0; n<10; n++){
  scanf("%1[\n]", c);
  printf("%d %s\n", n, c);
 }
 return 0;
}

If I just input enter , it actually works as expected (catching the new line and printing it). 如果我只是输入enter ,它实际上可以按预期工作(捕获新行并打印)。 However, if I input another character, it it goes through the loop until the end without waiting for any other input. 但是,如果我输入另一个字符,它会一直循环直到结尾,而无需等待任何其他输入。

Just use fgets() . 只需使用fgets() If the returned string is empty, stop. 如果返回的字符串为空,请停止。 If it is not empty, use sscanf() to parse it. 如果不为空,请使用sscanf()进行解析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM