【算法】【将字符串转换成int】

#include <stdio.h>
#include <error.h>

#define ERROR  -22

#define DEBUG	0
static int CheckValid(char *str)
{
	// debug
	#if DEBUG
	printf("%s\n", str);
	#endif
	
	char *ptr = str;
	if(!(*ptr=='-'||((*ptr-'0')>=0&&(*ptr-'0'<=9)))){
		goto out;
	}
	ptr++;
	while(*ptr){
		if(!((*ptr-'0')>=0&&(*ptr-'0'<=9))){
			goto out;
		}
		ptr++;
	}
	return 0;
out:
	fprintf(stderr, "%s is invalid\n", str);
	return ERROR;
}

static long int CharTolong(char *str)
{
	// debug
	#if DEBUG
	printf("%s\n", str);
	#endif
	long int ret = 0;
	int flag = 0;
	char *ptr = str;
	if(*ptr=='-'){
		flag = 1;
		ptr++;
	}
	while(*ptr){
		ret = ret*10+(*ptr-'0');
		ptr++;
	}
	if(flag==1)
		ret *=-1;
	return ret;
}
int main()
{ 
	char str1[] = "2345";
	if(!CheckValid(str1)){
		printf("%ld\n", CharTolong(str1));
	}
	
	char str2[] = "-456";
	if(!CheckValid(str2)){
		printf("%ld\n", CharTolong(str2));
	}
	
	char str3[] = "0678";
	if(!CheckValid(str3)){
		printf("%ld\n", CharTolong(str3));
	}
	
	char str4[] = "gy789";
	if(!CheckValid(str4)){
		printf("%ld\n", CharTolong(str4));
	}
	
	char str5[] = "890-8";
	if(!CheckValid(str5)){
		printf("%ld\n", CharTolong(str5));
	}
}

之前还使用过递归来计算,不过现在已经记不起来了

猜你喜欢

转载自blog.csdn.net/feifei_csdn/article/details/81176310