C语言 字符串值转换成整型数值的方法

在C语言中将字符串值转化成整型值有如下几种方法

1.使用atoi函数

  • atoi的功能就是将字符串转为整型并返回。
  • 它的描述为: 把参数 str 所指向的字符串转换为一个整数(类型为 int 型)。
  • 其声明为
int atoi(const char *str)
  • 它所在的头文件:stdlib.h
  • 该函数返回转换后的长整数,如果没有执行有效的转换,则返回零。

实例:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main(){
	int str1=0;
	char str2[10];
	strcpy(str2,"123456789");
	str1=atoi(str2);
	printf("%d",str1);
	//system("pause");
}
	运行结果为:123456789

2.使用sscanf函数

  • 它的声明为:
int sscanf(const char *str, const char *format, ...)
  • 返回值: 如果成功,则返回成功匹配和赋值的个数。如果到达文件末尾或发生读错误,则返回 EOF。

3.使用 -‘0’ 的方式

  • 这种方式是我在同学作业中看到的一种方法
    • 直接看实例

实例

#include<stdio.h>

void main() {
	int number[10] = { 0 };
	int i;
	char str[10];
	strcpy( str,"123456789" );
	for (i = 0; i<10; i++) {
		number[i] = str[i] - '0';
		printf("%-10d", number[i]);
	}
	system("pause");
}
运行结果:1		2		3		4		5		6		7		8		9		-48
发布了21 篇原创文章 · 获赞 2 · 访问量 1604

猜你喜欢

转载自blog.csdn.net/tothk/article/details/104147386