字符串转数值

#define _CRT_SECURE_NO_WARNINGS
#include 
#include 
const int N = 100;
int ch2num(char* p) {
	int len = strlen(p);
	int item = 1;
	int index = 0;
	if (p[0] == '-') {
		item = -item;
		index = 1;
	}
	int res = 0;
	for (; index < len; index++) {
		res = res * 10 + p[index] - '0';
	}
	return res*item;
}
int main()
{
	char s[6];
	int n;
	printf("Please input number string:");
	gets_s(s);
	int num = ch2num(s);
	printf("\nString to number is:");
	printf("%d\n", num);
	return 0;
}

你可能感兴趣的:(课堂检测,c语言)