天天看点

字符串删除空格及加减法

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

//下标法
//void eatspace(char *str) { //删除空格
//	int i = 0;
//	int j = 0;
//
//	/*while (str[i] != '\0') {  //去空格
//		str[i] = str[j];
//
//		if (str[i] != ' ') {
//			i++;
//		}
//		j++;
//
//
//
//	}*/
//	while ((str[i] = str[j++])!='\0') {	//去加号
//		if (str[i] != '+') {
//			i++;
//		}
//	}
//}


//指针法
void eatspace(char *str) {
	char *p1 = str;
	char *p2 = str;
	/*while (*p1 != '\0') {
		*p1 = *p2;
		if (*p1 != ' ') {
			p1++;
		}
		p2++;
	}*/



	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;
		}

		//index++;//循环遍历
	}


}


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);

	printf("\n计算表达式%f", fenxi(str));

	system("pause");
}
           

继续阅读