fscanf()问题
- C/C++ code
int getsth(FILE* & filein, int &obj1, char &obj2){ if(fscanf(filein,"%d",&obj1) == 1) { printf("%d\n",obj1); return 1; } if(fscanf(filein,"%c",&obj2) == 1) { if(obj2 == ' ') { printf("空格\n"); return getsth(filein, obj1, obj2); } else { printf("%c\n",obj2); return 2; } }}int main(){ FILE *fp = fopen("data.txt", "r"); int obj1 = 0; char obj2 = '\0'; int state = getsth(fp, obj1, obj2); while(state == 1 ||(state == 2 && obj2 != '\n')) { if(state == 1) { state = getsth(fp, obj1, obj2); } else { break; } } return 0;}data.txt:
4 + 3
程序运行如下:
4
空格
3
为什么没有打印加号?
[解决办法]
int getsth(FILE* & filein, int &obj1, char &obj2)
{
int pos=ftell(filein);
。。。。。
可以跟踪一下文件指针,会有惊喜的