准确读入一或两个字符串
我有一个程序接受来自命令行的输入。虽然所有可用命令都是一个字符串,但其中一些命令需要辅助字符串来进一步定义操作。
例如,“end”是一个命令,“add foo”是第二个命令。
我的代码可以很好地处理 2 个字符串输入,但是当我尝试访问单个字符串命令(例如“end”)时,程序会等待更多输入,而不是立即执行操作。
有什么方法可以让程序只读取一行(最多可能有两个字符串)而不是像现在这样?
目前的实施方式如下:
while(1)
{
scanf("%s%s", commandString,floorPath);
if(!strcmp(commandString,"end") return;
//I've got several of these as an "if / else", but there's no
//need to reprint them here.
}
I have a program that accepts input from the command line. While all of the available commands are one string, several of the commands require a secondary string to further define the action.
e.g. "end" is one command, and "add foo" is a second.
My code handles the 2 string inputs fine, but when I try to access a single string command (such as "end") the program waits for more input instead of acting immediately.
Is there some way I can get the program to read in exactly one line (which may have up to two strings) rather than the way it is now?
Here's how it's currently implemented:
while(1)
{
scanf("%s%s", commandString,floorPath);
if(!strcmp(commandString,"end") return;
//I've got several of these as an "if / else", but there's no
//need to reprint them here.
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一个替代方案:
自从我用 C 编码以来已经有一段时间了,但我记得 scanf 遇到了问题(所以我曾经使用 getline())。 strtok 函数将解析出字符串,返回时您可以检查是否成功并处理数组 cmd。我相信你必须为此包含 stdio.h、stdlib.h 和 string.h。我的C有点生疏,所以请原谅语法错误。
Here is an alternative:
It's been a while since I have coded in C, but I remember having problems with scanf (so I used to use getline()). The strtok function will parse out the string, on return you can check for success and work on the array cmd. I believe you have to include stdio.h, stdlib.h and string.h for this. My C is a bit rusty, so please excuse the syntax errors.
MByD 所说的,或者,读取一行,然后与
scanf()
分开解析您读入的行,看看它是一个字命令还是两个字命令,并采取适当的方法行动。What MByD said, or alternatively, read a single line and then separately from the
scanf()
parse the line you read in and see if it is a one word command or a two word command and take the appropriate actions.单独读取第一个字符串,并根据输入决定是否需要读取另一个字符串。
Read the first string alone, and depending on the input decide if there is a need to read another string or not.