求助:为什么输不出+号?
- C/C++ code
//问题一:输入2 3 +'\n'输不出+号,但输入2 3 + '\n'时就能输出+号,为嘛?#include <stdio.h>#include <ctype.h>#define NUM 'f'int line = 0;int c = 0;int getop(void){ while ((c = getchar())== ' ' || c == '\t') { ; } if (!isdigit(c)) { return c; } stdin->_ptr--; scanf("%d", &line); return NUM;}void main(){ int number = 0; int oper = 0; printf("input:\n"); while (getop() != '\n') { printf("c = %c\n", c); }}//问题二:输入2 3 + 4 +'\n' 输不出最后一个+号,但输入2 3 + 4 + '\n'就能输出最后一个+号,为嘛?#include <stdio.h>#include <ctype.h>#define NUM 'f'void main(){ int number = 0; int oper = 2; printf("input:\n"); while (oper != '\0') { if (scanf("%d", &number) == 1) { printf("number = %d\n", number); oper = NUM; } else if (*stdin->_ptr == '\n' || *stdin->_ptr == ' ') { stdin->_ptr--; if (scanf("%c", &oper) == 1) { printf("oper = %c\n", oper); } } else if (scanf("%c", &oper) == 1) { printf("oper = %c\n", oper); } } }[解决办法]
仅供参考
- C/C++ code
#include <stdio.h>char s[]="123 ab 4";char *p;int v,n,k;void main() { p=s; while (1) { k=sscanf(p,"%d%n",&v,&n); printf("k,v,n=%d,%d,%d\n",k,v,n); if (1==k) { p+=n; } else if (0==k) { printf("skip char[%c]\n",p[0]); p++; } else {//EOF==k break; } } printf("End.\n");}//k,v,n=1,123,3//k,v,n=0,123,3//skip char[ ]//k,v,n=0,123,3//skip char[a]//k,v,n=0,123,3//skip char[b]//k,v,n=1,4,2//k,v,n=-1,4,2//End.
[解决办法]
我在你的上面加了一行,验证了我的想法是对的:
- C/C++ code
#include <stdio.h>#include <ctype.h>#define NUM 'f'int line = 0;char c = 0;int getop(void){ while ((c = getchar())== ' ' || c == '\t') { ; } if (!isdigit(c)) { return c; } stdin->_ptr--; stdin->_cnt++;/*这里加上以后,你说的那个现象不存在了,哎,冥思苦想了一夜 啊!!看来要好好学习啊!!*/ scanf("%d", &line); printf("%d\n",line); return NUM;}int main(){ int number = 0; int oper = 0; printf("input:\n"); while (getop() != '\n') { printf("c = %c\n", c); }}