如何在scanf()的末尾检测到空格或换行符? [英] How can I detect a space or newline at the end of scanf()?
问题描述
我正在编写一个程序,在该程序中,我必须接受来自用户的命令,例如shell,用户可以在其中为环境变量设置值.我遇到的问题是,如果用户键入set var var-value
,我需要知道用户键入的是空格,而不只是set
,然后按Enter,这是另一个命令.如何确定用户是否按下空格或使用scanf()
输入?
I'm writing a program where I have to accept commands from the user like a shell where the user can set values for environment variables. The problem I'm having is if the user types set var var-value
I need to know the user typed a space instead of just set
and pressed enter which is a different command. How can I determine if the user pressed space or enter using scanf()
?
推荐答案
您将知道用户按下回车键,因为scanf()
直到用户这样做才返回.如果您尝试按用户类型实时读取字符,则scanf()
将不适合您.您将需要使用getchar()
,getch()
或getche()
功能,或操作系统提供的用于读取键盘输入的功能.逐个读取字符到数组中,在读取时扫描空格和Enter键.
You'll know the user pressed enter because scanf()
won't return until the user does so. If you're trying to read characters in real time as the user types, scanf()
will not work for you. You will need to use the getchar()
, getch()
or getche()
functions, or a function provided by the OS for reading keyboard input. Read the characters one by one into an array, scanning for spaces and the enter key as you read.
另请参见此问题.
这篇关于如何在scanf()的末尾检测到空格或换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!