在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);
}
運行結果為: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