C、从输入中读取简单的公式字符串

发布于 2024-10-02 18:49:29 字数 647 浏览 2 评论 0原文

对于作业,我们需要输入简单的公式(例如3*24+1050/16等)和仅使用加法、减法和位移位来计算结果(和其余部分)。无论如何,我可以使用三个后续输入读取,但是我想尝试使用 fgets()sscanf() 一次性获取公式。这就是我所拥有的:

int *v;  // value (left side)
int *m;  // modifier (right side)
char *o; // operant

int res = sscanf(buffer,"%d%s%d",v,o,m);

但自然地,这不起作用,因为 o 获取字符串的所有剩余部分,而 m 没有任何内容(m code> 等于声明的位置和时间的任何值)

现在,完成此操作的正确方法是什么?

注意:我正在使用修剪功能 修剪多余的空格。

for a homework, we need to input simple formulas (such as 3*2, 4+10, 50/16, etc.) and calculate the result (and rest) using only addition, subtraction, and bit shifting. Anyway, I could use three subsequent input reading, however I thought I'd try getting the formula in one pass using fgets() and sscanf(). Here is what I have :

int *v;  // value (left side)
int *m;  // modifier (right side)
char *o; // operant

int res = sscanf(buffer,"%d%s%d",v,o,m);

But naturally, this does not work, because o gets all the remaining portion of the string, leaving m with nothing (m equals whatever value is where and when it is declared)

Now, what would be the proper way to accomplish this?

NOTE : I'm using a trim function to trim extra spaces.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

十级心震 2024-10-09 18:49:29

尝试使用 %c 而不是 %s。如果运算符始终是单个字符,并且运算符和操作数之间没有空格,则这应该有效。

顺便说一句,您是否正在初始化 vmo 来实际指向某些东西?这样做会好得多:

int v;
int m
char o;

int res = sscanf(buffer, "%d%c%d", &v, &o, &m);

正如我的“C 编程简介”教授常说的:“C 很危险。练习安全的 C!”。

Try %c instead of %s. If the operator is always a single character, and there are no spaces between the operator and the operands, this should work.

By the way, are you initializing v, m, and o to actually point to something? It would be much better to do this:

int v;
int m
char o;

int res = sscanf(buffer, "%d%c%d", &v, &o, &m);

As my "Intro to Programming in C" professor used to say: "C is dangerous. Practice safe C!".

人│生佛魔见 2024-10-09 18:49:29

您可以使用 %[-+*/] (与您的一组运算符)来确保该运算符字符串仅获取运算符字符。

You may use %[-+*/] (with your set of operators) to ensure, that operator string gets only operator characters.

沙与沫 2024-10-09 18:49:29

由于您没有多余的空格,并且运算符都是一个字符长,因此您可以使用 %c 来填充 o

Since you don't have extraneous spaces and operators are all one character long, you could use %c to fill in o.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文