C 语言:如何读取像“SomeWord(Int)”这样的输入,没有空格,只有一个单词,然后是圆括号内的数字
我需要从用户那里获取单行输入,并且有 5 个值,我从该输入中提取这些值(“c”需要为 5)。输入的格式是:“单词(数字)数字单词句子”。但问题出在“单词(数字)”输入区域。我无法获取它,以便从输入的该部分读取值并将其存储在命令和 num1 中。下面是我尝试过的代码,但它似乎不起作用。
c = sscanf (line, "%s(%d) %d %s %128[^\n]", command, num1, num2, message, message2);
当我这样做时,用户输入“单词(数字)数字单词句子”,括号前有一个空格,同时还将代码从 %s(%d)< /code> 到
%s (%d)
,这似乎有效。但我需要它的值 command
和 num1
之间没有任何空格。
I need to take input from the user that is a single line and has 5 values which I extract from that input ('c' needs to be 5). The input is this format: "word(number) number word sentence". But the problem is with the "word(number)" input area. I cannot get it so that the values are read from that part of the input and stored in command, and num1. Below is the code I tried but it does not seem to be working.
c = sscanf (line, "%s(%d) %d %s %128[^\n]", command, num1, num2, message, message2);
When I make it so that the user enters "word (number) number word sentence" instead, with a space before the brackets, with also changing the code from %s(%d)
to %s (%d)
, that seems to work. But I need it without any space between the values command
and num1
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要从第一个字符串中排除括号。假设“命令”严格是字母数字和下划线,您可以这样做:
此外,您需要在
num1
和num2
上使用&符号;也许那些是拼写错误?为了安全起见,您应该像对
message2
那样对command
和message
进行长度限制。假设“char command[21], message[33];”,这将是:You will need to exclude the parenthesis from the first string. Assuming the "command" is strictly alphanumeric and underscore, you can do this:
Also, you need ampersands on
num1
andnum2
; perhaps those were typos?For safety, you should put length limits on
command
andmessage
as you do formessage2
. Assuming 'char command[21], message[33];`, this would be: