C - printf 和 scanf - 如何终止输入?
我正在开发一个用 C 编写的简单应用程序。我在 Unix 环境中工作。
我的应用程序正在执行一些简单的 I/O。我使用 printf 提示用户进行一些输入,然后使用 scanf 获取该输入。
问题是,我不知道如何告诉我的应用程序我已准备好在输入值后继续。输入“enter”会提供一个换行符“\n”,这是有意义的。 Control-d 确实允许 scanf 捕获我的输入,但似乎忽略任何后续的 scanf 指令。
有人可以帮我吗?
printf("Enter name\n");
scanf("%s",input);
printf("%s",input);
printf("enter more junk\n")
scanf("%s",morestuff); /* cntrl+d skips this*/
I am working on a simple application written in C. I am working in a Unix environment.
My application is doing some simple I/O. I use printf to prompt the user for some input and then use scanf to get that input.
The problem is, I don't know how to tell my application that I am ready to proceed after entering in a value. Typing 'enter' provides a newline '\n' which makes sense. Control-d does allow scanf to capture my input but seems to ignore any subsequent scanf instructions.
Can someone help me out?
printf("Enter name\n");
scanf("%s",input);
printf("%s",input);
printf("enter more junk\n")
scanf("%s",morestuff); /* cntrl+d skips this*/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
检查
scanf()
的返回值。一旦到达 EOF(由于您输入 control-D),每次都会失败,直到您清除错误为止。使用
scanf()
时要小心;我发现它在现实世界中很难使用,因为它无法让我控制我认为需要的错误处理。我建议使用 fgets() 或等效函数来读取数据行,然后使用 sscanf() - 一个更文明的函数 - 来解析数据。另请参阅一个松散相关的问题:SO 3591642。
Check the return value from
scanf()
. Once it has gotten EOF (as a result of you typing control-D), it will fail each time until you clear the error.Be cautious about using
scanf()
; I find it too hard to use in the real world because it does not give me the control over error handling that I think I need. I recommend usingfgets()
or an equivalent to read lines of data, and then usesscanf()
- a much more civilized function - to parse the data.See also a loosely related question: SO 3591642.
[编辑:这个答案是不正确的,正如我在下面所说的,我也在学习]
你尝试过 CTRL-Z 吗?
这会将 EOF 发送到 scanf,根据其手册页,这应该使 scanf 移动到下一个字段。由于您仅输入了一个字符串作为输入格式,因此应该终止 scanf。
我现在无法对此进行测试,但您可以尝试一下。
手册页位于:
http://www.slac.stanford.edu/comp/unix/package/rtems/doc/html/libc/libc.info.scanf.html
[EDIT: This answer is incorrect, as I stated below, I'm learning as well]
Have you tried CTRL-Z?
That sends EOF to scanf, which, according to its man page, should make scanf move to the next field. As you've entered only a string as the input format, that should terminate the scanf.
I can't test this right now, but you can give it a shot.
Man page is here:
http://www.slac.stanford.edu/comp/unix/package/rtems/doc/html/libc/libc.info.scanf.html