C 语言:如何读取像“SomeWord(Int)”这样的输入,没有空格,只有一个单词,然后是圆括号内的数字

发布于 2025-01-13 11:33:09 字数 482 浏览 4 评论 0原文

我需要从用户那里获取单行输入,并且有 5 个值,我从该输入中提取这些值(“c”需要为 5)。输入的格式是:“单词(数字)数字单词句子”。但问题出在“单词(数字)”输入区域。我无法获取它,以便从输入的该部分读取值并将其存储在命令和 num1 中。下面是我尝试过的代码,但它似乎不起作用。

c = sscanf (line, "%s(%d) %d %s %128[^\n]", command, num1, num2, message, message2);

当我这样做时,用户输入“单词(数字)数字单词句子”,括号前有一个空格,同时还将代码从 %s(%d)< /code> 到 %s (%d),这似乎有效。但我需要它的值 commandnum1 之间没有任何空格。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

南汐寒笙箫 2025-01-20 11:33:09

您需要从第一个字符串中排除括号。假设“命令”严格是字母数字和下划线,您可以这样做:

c = sscanf(line, "%[_a-zA-Z0-9](%d) %d %s %128[^\n]", command, &num1, &num2, message, message2);

此外,您需要在 num1num2 上使用&符号;也许那些是拼写错误?

为了安全起见,您应该像对 message2 那样对 commandmessage 进行长度限制。假设“char command[21], message[33];”,这将是:

"%20[_a-zA-Z0-9](%d) %d %32s %128[^\n]"

You will need to exclude the parenthesis from the first string. Assuming the "command" is strictly alphanumeric and underscore, you can do this:

c = sscanf(line, "%[_a-zA-Z0-9](%d) %d %s %128[^\n]", command, &num1, &num2, message, message2);

Also, you need ampersands on num1 and num2; perhaps those were typos?

For safety, you should put length limits on command and message as you do for message2. Assuming 'char command[21], message[33];`, this would be:

"%20[_a-zA-Z0-9](%d) %d %32s %128[^\n]"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文