返回信息流写一个简单计算器,编译一直没问题,但是一运行就崩,后来把带颜色行换成“op = &buffer[index++];”
就ok了,我不明白,这到底为什么,两者有什么区别吗?
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<ctype.h>
#define len 256
int main()
{
char buffer[len] = {NULL};
char strNum[30] = {NULL};
char *pbuffer = buffer;
char *op = NULL;
int index , to = 0;
size_t inputLen =0;
float result,num = 0;
while(strcmp(fgets(buffer,len,stdin),"quit\n")!=0)
{
inputLen = strlen(buffer);
buffer[--inputLen] = '\0';
for(to = 0,index = 0;index<inputLen;index++)
if(*(pbuffer+index) != ' ')
*(pbuffer+to++)==*(pbuffer+index);//去掉空格
inputLen = strlen(buffer);
index = 0;
to = 0;
//确定第一个result
if(*pbuffer == '=')
index++;
else
{
if(*(pbuffer+index) == '+'||*(pbuffer+index) == '-')
*(strNum+to++) = *(pbuffer+index++);
for(;isdigit(*(pbuffer+index));index++)
*(strNum+to++) = *(pbuffer+index);
if(*(pbuffer+index) == '.')
{
*(strNum+to++) = *(pbuffer+index++);
for(;isdigit(*(pbuffer+index));index++)
*(strNum+to++) = *(pbuffer+index);
}
*(strNum+to) = '\0';
if(inputLen>0)
result = atof(strNum);
}
for(;index<inputLen;)
{
[color=#FFF8DC]*op = buffer[index++];[/color]
to = 0;
*strNum = NULL;
if(buffer[index]=='+' || buffer[index]=='-')
*(strNum+to++) = *(buffer+index++);
for(;isdigit(*(pbuffer+index));index++)
*(strNum+to++) = *(pbuffer+index);
if(*(pbuffer+index) == '.')
{
*(strNum+to++) = *(pbuffer+index++);
for(;isdigit(*(pbuffer+index));index++)
*(strNum+to++) = *(pbuffer+index);
}
*(strNum+to) = '\0';
num = atof(strNum);
// if(*op = '+')
// result += num;
// if(*op = '-')
// result -= num;
// if(*op = '*')
// result *= num;
// }
printf("\n=%f\n",num);
}
}
return 0;
}
这是一条镜像帖。来源:北邮人论坛 / cpp / #94032同步于 2016/11/23
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
【问题】指针的小小问题
yizisad
2016/11/23镜像同步6 回复
订阅后,新回复会通过你的通知中心匿名送达。
6 条回复
嘿嘿,因为是指针章节的题目,所以被强制用了
【 在 nuanyangyang 的大作中提到: 】
: 你直接写buffer[index]不好吗,非得*(pbuffer+index)
:
发自「贵邮」