C、从输入中读取简单的公式字符串
对于作业,我们需要输入简单的公式(例如3*2
、4+10
、50/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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试使用
%c
而不是%s
。如果运算符始终是单个字符,并且运算符和操作数之间没有空格,则这应该有效。顺便说一句,您是否正在初始化
v
、m
和o
来实际指向某些东西?这样做会好得多:正如我的“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
, ando
to actually point to something? It would be much better to do this:As my "Intro to Programming in C" professor used to say: "C is dangerous. Practice safe C!".
您可以使用
%[-+*/]
(与您的一组运算符)来确保该运算符字符串仅获取运算符字符。You may use
%[-+*/]
(with your set of operators) to ensure, that operator string gets only operator characters.由于您没有多余的空格,并且运算符都是一个字符长,因此您可以使用
%c
来填充o
。Since you don't have extraneous spaces and operators are all one character long, you could use
%c
to fill ino
.