专业编程基础技术教程

网站首页 > 基础教程 正文

把字符串转换为数字(字符串如何转化为数字型)

ccvgpt 2025-04-06 14:12:20 基础教程 11 ℃

如果写程序需要使用命令行形参,但是命令形参数被读取字符串,因此,必须要使用数值先把字符串转换为数字.如果需要整数,可以使用atio()函数(用于字符数字转换成整数),该函数接受一个字符串作为参数,返回相应的整数值

#include
#include//把字符串转成数值
int main(int argc,char* argv[])
{
	int i, times;
	printf("argc=%d\n", argc);
	if (argc < 2 || (times = atoi(argv[1])) < 1)//取出命令行角标为1的字符
	{
		printf("usage:%s positive-number\n", argv[0]);
	}
	else
	{
		for (i = 0; i < times; i++)
		{
			puts("hello,good looking!");
		}
	}
	system("pause");
	return 0;
}
命令行参数3被存储为字符串3\0,atio()函数把该字符串转换为整数值3,然后被值赋给times,该值确定了执行
for循环的次数.如果运行该程序时没有提供命令行参数,那么argc<2为真.如果命令行参数不是数字,atio()函数
返回0.
  //strtlo函数的使用
#define LIM 30
//char* s_gets(char* st, int n);
int main()
{
	char number[LIM];
	char* end;//指针
	long value;
	puts("enter a number (empty line to quit):");
	while (gets_s(number, LIM) && number[0] != '\0')//从键盘录入一个字符串超过范围就会被截断
	{
		value = strtol(number, &end, 10);十进制
		printf("base 10 input,base 10 output:%ld,stopped at %s (%d)\n", value, end, *end);
		value = strtol(number, &end, 16);十六进制
		printf("base 16 input,base 10 output:%ld,stopped at %s (%d)\n", value, end, *end);
    puts("next number:");
	}
	
	system("pause");
	return 0;
}

把字符串转换为数字(字符串如何转化为数字型)

最近发表
标签列表