stdlib中自带str与int/long之间的互转:
itoa、ltoa(int, char*, int)
strtoi、strtol(char*, char**, int)
关于scanf读取数据的问题:
1 #include
2 3 int main(){ 4 char data[15] = "hello,world!"; 5 printf("%s\n",data); 6 scanf("%s",data); 7 printf("%s\n",data); 8 int i; 9 for(i=0;i<15;i++){ 10 printf("%c ",data[i]); 11 } 12 if(data[3]=='\0'){ 13 printf("hello\n"); 14 } 15 if(data[3]=='\n'){ 16 printf("hello\n"); 17 } 18 19 20 printf("%d--%d\n",'\0','\n'); 21 22 return 0; 23 } /* hello,world! acd acd a c d o , w o r l d ! hello 0--10 */
☞ 模拟stdlib.h中strtoi(char*,char**,redix)/strtol(char*,char**,redix):
#include
int charArrayToInt(char* data){
if(data==NULL){
return -1;
}
int length = 0;
while(data[length]!='\0'){
length++;
}
int i = 0;
int j = 0;
for(;i='0'){}else{
return -1;
}
}
int res = 0;
for(i=0;i
☞ 将int类型转换为字符串:sprintf
int intLength(int num){
char buff[15];
sprintf(buff,"%d",num);
int length = 0;
while(buff[length]!='\0'){
length++;
}
return length;
}
检测字符串是否为指定长度数字:
#include
/*
成功返回实际值
失败:
-1:不能以0开头
-2:格式有误
-3:长度错误
*/
int check(char *data,int len){
if(data==NULL){
return -1;
}
int length=0;
while(data[length]!='\0'){
length++;
}
int i=0;
int j=0;
if(data[0]==0){
return -1;
}
for(;i='0'){}else{
return -2;
}
}
// 长度判断
if(length!=len){
return -3;
}
return 0;
}
// 测试
int main(){
char *data1 = "a123";
char *data2 = "1a23";
char *data3 = "123a";
char *data4 = "123";
printf("%d\n",check(data1,3));
printf("%d\n",check(data2,3));
printf("%d\n",check(data3,3));
printf("%d\n",check(data4,3));
printf("%d\n",check(data4,4));
return 0;
}