除“+”和“

编程入门 行业动态 更新时间:2024-10-19 20:40:04
除“+”和“ - ”外,正确扫描字符(Scanning the characters properly except '+' and '-')

我正在尝试扫描如下的算术表达式: 4+3-2*6*(3+4/2)#

我尝试的是遵循代码。 它运行正常并且正确扫描每个角色,除了'+'和'-' 。

为什么它不扫描只有两个特定字符!

void scan(){ int n,tmp,digit_no; char c; scanf("%c",&c); while(c!='#'){ if(isdigit(c)) { tmp=c; scanf(" %d",&n); digit_no=numPlaces(n); n=(tmp-48)*ipow(10,digit_no)+n; push_n(n); n=0; } else if(c=='+' || c=='-' || c=='*' || c=='/' || c=='(' || c==')' || c=='=' || c=='^') push_o(c); scanf("%c",&c); } }

I am trying to scan an arithmetic expression like : 4+3-2*6*(3+4/2)#

What I tried is following code. It's running fine and scanning each character properly except '+' and '-'.

Why it is not scanning only two particular characters!

void scan(){ int n,tmp,digit_no; char c; scanf("%c",&c); while(c!='#'){ if(isdigit(c)) { tmp=c; scanf(" %d",&n); digit_no=numPlaces(n); n=(tmp-48)*ipow(10,digit_no)+n; push_n(n); n=0; } else if(c=='+' || c=='-' || c=='*' || c=='/' || c=='(' || c==')' || c=='=' || c=='^') push_o(c); scanf("%c",&c); } }

最满意答案

不要获取char ,测试数字,扫描int然后尝试将它们放在一起。 这使代码的意图失败,输入像"3-2" , "1 23" , "1+23"这样的输入以及@John Bollinger解释为scanf("%d",&n)正在消耗+ - 。

而是将数字放回stdin ,然后扫描int 。

if(isdigit(c)) { ungetc(c, stdin); scanf("%d",&n); // cannot fail as first character is a digit - may overflow though push_n(n); n=0; }

还建议检测EOF并使用is...()函数正确。

// char c; // scanf("%c",&c); int c; // while(c!='#'){ while((c = fgetc(stdin)) !='#' && c != EOF) { ... // scanf("%c",&c); }

细节: is...()期望在unsigned char和EOF范围内的unsigned char 。 当值为负时,使用char调用它们是一个问题。

Do not get a char, test for a digit, scan an int and then try to put them together. This fails the code's intent with input like for input like "3-2", "1 23", "1+23" as well explained by @John Bollinger as scanf("%d",&n) is consuming the + -.

Instead put the digit back into stdin and then scan for the int.

if(isdigit(c)) { ungetc(c, stdin); scanf("%d",&n); // cannot fail as first character is a digit - may overflow though push_n(n); n=0; }

Also suggest to detect EOF and use is...() functions correctly.

// char c; // scanf("%c",&c); int c; // while(c!='#'){ while((c = fgetc(stdin)) !='#' && c != EOF) { ... // scanf("%c",&c); }

Detail: is...() expects an int in the range of unsigned char and EOF. Calling them with a char is a problem when the value is negative.

更多推荐

scan,扫描,电脑培训,计算机培训,IT培训"/> <meta name="description" con

本文发布于:2023-04-29 11:16:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1336352.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!