【C语言练习题】字符串转换整数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/feit2417/article/details/85334713

《C和指针》 习题7.11

问题

为下面的函数原型编写函数定义:
int ascii_to_integer(char *str);
这个字符串参数必须包含一个或者多个数字,函数应该把这些数字字符转换为整数并返回这个整数。
如果字符串参数包含了任何非数字字符,函数就返回零。请不必担心算数溢出。
提示:这个技巧很简单:你每发现一个数字,把当前值乘以10,并把这个值和新的数字所代表的值相加

代码

#include <stdio.h>

#define N 20

int ascii_to_integer( char *string );



void main( void )
{
	int temp  = 0;
	char strings[N] = {0};
	printf(">>");
	scanf("%s",strings);
	
	printf("input is:%s\n",strings);

	temp = ascii_to_integer( strings );
	printf("output:%d\n",temp);
}

/*把一个数字字符串转换成一个整数
 *输入:字符串首地址
 *输出:转换后的整数
 */
int ascii_to_integer( char *string )
{
	int value = 0;

 	while( *string >= '0' && *string <= '9' )
	{
		value *= 10;	//相当于十进制左移一位
		value += *string - '0'; //将字符转换成int型存放到value最低位
		string++;	//指针偏移到下一个位置
	}

	if( *string != '\0' )
	{//字符串中含有非'0'~'9'的字符,返回失败
		return -1;
	}

	return value;
}

展示

猜你喜欢

转载自blog.csdn.net/feit2417/article/details/85334713