scanf函数:"%[^ \\ n] QUOT;跳过第二个输入,但" %[^ \\ n] QUOT;才不是。为什么? [英] scanf: "%[^\n]" skips the 2nd input but " %[^\n]" does not. why?

查看:201
本文介绍了scanf函数:"%[^ \\ n] QUOT;跳过第二个输入,但" %[^ \\ n] QUOT;才不是。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下code:

#include <stdio.h>

int main (void)
{
  char str1[128], str2[128], str3[128];

  printf ("\nEnter str1: ");
  scanf ("%[^\n]", str1);
  printf ("\nstr1 = %s", str1);

  printf ("\nEnter str2: ");
  scanf ("%[^\n]", str2);
  printf ("\nstr2 = %s", str2);

  printf ("\nEnter str3: ");
  scanf ("%[^\n]", str3);
  printf ("\nstr2 = %s", str3);

  printf ("\n");
  return 0;
}

当它仅执行首 scanf函数停止的提示。该计划不会停止下一个 scanf函数秒。但是,如果格式字符串是从%[^ \\ n]更改为%[^ \\ n](注意之前空格),然后它工作正常。是否从previous输入缓冲区一些现有的换行符被自动接受?但是潮红标准输入不解决这个问题。

When it is executed only the first scanf stops for the prompt. The program does not stop for the next scanf s. But if the format string is changed from "%[^\n]" to " %[^\n]" (note the blank space before %), then it works okay. Does some existing newline character from the previous input buffer is automatically accepted ? But flushing stdin does not solve this.

什么是这个原因。

推荐答案

您只需要'消耗'的的'\\ n'字符,你读过之后,你想。使用以下格式的指令:

You just need to 'consume' the '\n' character after you've read what you want. Use the following format directive:

"%[^\n]%*c"

到换行符到字符串你传递这将读到的一切,那么将消耗一个字符(新行),而不将其分配到任何东西(即'*'为分配燮pression')

Which will read everything up to the newline into the string you pass in, then will consume a single character (the newline) without assigning it to anything (that '*' is 'assignment suppression').

否则,换行留在输入流中等待立即终止后续%[^ \\ n]格式的指令。

Otherwise,the newline is left in the input stream waiting to immediately terminate the the subsequent "%[^\n]" format directives.

与添加一个空格字符格式指令(%[^ \\ n])的问题在于空间将匹配的任何空白。所以,它会吃从previous输入的结束的换行,但它也将吃任何其他空白(包括多个新行)。

The problem with adding a space character to the format directive (" %[^\n]") is that the space will match any white space. So, it will eat the newline from the end of the previous input, but it will also eat any other whitespace (including multiple newlines).

更新您的例子:

  char* fmt = "%[^\n]%*c";

  printf ("\nEnter str1: ");
  scanf (fmt, str1);
  printf ("\nstr1 = %s", str1);

  printf ("\nEnter str2: ");
  scanf (fmt, str2);
  printf ("\nstr2 = %s", str2);

  printf ("\nEnter str3: ");
  scanf (fmt, str3);
  printf ("\nstr2 = %s", str3);

  printf ("\n");

这篇关于scanf函数:&QUOT;%[^ \\ n] QUOT;跳过第二个输入,但&QUOT; %[^ \\ n] QUOT;才不是。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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