能去除空格和计算小数的加减法
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
//void eatspace(char *str)
//{
// int i = 0;
// int j = 0;
// while ((str[i]=str[j++])!='\0')
// {
// if (str[i] != '+')
// {
// i++;
// }
// }
//
// /*while (str[i]!='\0')
// {
// str[i] = str[j];
// if (str[i] !=' ')
// {
// i++;
// }
//
// j++;
//
//
// }*/
//
//
//
//}
void eatspace(char *str)
{
char *p1 = str;
char *p2 = str;
//while (*p1!='\0')
//{
// *p1 = *p2;
// if (*p1!=' ')
// {
// p1++;
// }
// p2++;
//}
//p2 = p2 + 6;
while ((*p1=*(p2 ++))!='\0')
{
if (*p1!=' ')
{
p1++;
}
}
}
int isnum(char ch)//判断是否数字
{
int is = 0;
if (ch>='0' && ch<='9')
{
is = 1;
}
return is;
}
double getnum(char *str, int *pindex)
{
double value = 0.0;
int index = *pindex;
while ( isnum( *(str+index) ))//str[index]
{
value = value * 10 + (str[index] - '0');//字符转整数
index++;//往前移动
}
//
if (*(str+index) =='.')
{
double xiaoshu = 1.0;
while (isnum( *(str+ ++index) ))//循环到小数点后面的非数字
{
xiaoshu /= 10;//小数
value += xiaoshu*(*(str + index) - '0');
}
}
*pindex = index;//改变一个外部变量需要地址
return value;
}
double fenxi(char *str)
{
double value = 0.0;
int index = 0;
value = getnum(str, &index);//获取第一个数据
//index+
while (1)
{
char ch = *(str + index);//取出字符
index++;//循环遍历
switch (ch)
{
case '\0':
return value;
case '+':
value += getnum(str, &index);
break;
case '-':
value -= getnum(str, &index);
break;
default:
break;
}
}
}
void main()
{
char str[1024] = { 0 };//缓冲区
scanf("%[^\n]", str);
printf("要计算的是%s\n", str);
eatspace(str);
printf("要计算的是%s\n", str);
int index = 0;
double value = getnum(str, &index);
printf("第一个获取的数据%f", value);
cout <<"index="<< index << endl;
printf("\n计算表达式%f", fenxi(str));
system("pause");
}