c语言字符串转换整数
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define bool _Bool
#define true 1
#define false 0
bool strToInt(char *s, long *num)
{
bool minus = false;
bool first = true;
while(*s != '\0'){
if (*s == '+' && first) {
s++;
} else if(*s == '-' && first) {
minus = true;
s ++;
} else {
first = false;
if (*s < '0' || *s >'9')
{
printf("The string is not Int num\n");
return false;
}
*num = *num *10 + (*s-'0');
s ++;
}
}
if (minus) {
*num = 0 - *num;
}
return true;
}
int main()
{
char *s = "-123";
long num = 0;
if(strToInt(s, &num)) {
printf("num = %ld\n", num);
}
}
|
实际上,c 语言库中有此函数atoi()
char *c = "345";
printf("c = %d\n", atoi(c));
阅读(500) | 评论(0) | 转发(0) |