我正在尝试扫描如下的算术表达式: 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 '-'.
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); } }Why it is not scanning only two particular characters!
最满意答案
不要获取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
发布评论