Converting String to Integer in C Language

Require

1. Only positive and negative signs and numbers are included in the input.
2. The plus or minus sign only appears in the first place.

learn

(1) The negative Ascii code is 45, and the positive Ascii code is 43.
(2) The conversion between char type characters and integer types needs to be cut by 48. For example, if char a='6' is converted to int type, it will be
demonstrated as int b=a-48.
(3) If the first bit is a symbol, record it with flag, and finally make corresponding changes.

#include<stdio.h>
int main(){
    
    
	char a='6';
	int b=a-48;
	printf("%d",b);
	return 0;
}

output result
insert image description here

basic idea

1. First traverse the string s, convert each character into a number, store it in an integer array a, and record the trailing subscript of a.
2. Traverse the integer array a and multiply each item by the corresponding order of magnitude and add them.
insert image description here

How to multiply by the corresponding order of magnitude, since the integer array a is traversed from i=0, each item is multiplied by the top-i power of 10.
is intended as follows.
insert image description here

traverse while summing.
insert image description here

code

Find the nth power function of 10

//10的n次方 
int g(int n){
    
    
	int t=1;
	int i;
	if(n==0){
    
    //10的0次方等于1
		return 1;
	} else{
    
    
		for(i=0;i<n;i++){
    
    
			t=t*10;
		}
	}
	return t;
}

Convert string s to integer function

int f(char* s){
    
    
	int a[100];
	int top=-1;
	int i;
	int flag=0;//如果第一位是符号,则用flag记录 
	int sum=0;//记录最后的返回值 
	
	for(i=0;s[i]!='\0';i++){
    
    //遍历字符串s 
		if(s[i]=='-'||s[i]=='+'){
    
    //如果是符号则放入flag中 
			flag=s[0];
		}else{
    
    
			top++;
			a[top]=s[i]-48; //字符转整型减48 
		}
	}
	
	for(int i=0;i<=top;i++){
    
    //遍历整型数组a 
		sum=sum+a[i]*g(top-i);//每一项乘以对应的数量级 
		
	}
	
	if(flag==45){
    
    //判断符号 
		return -1*sum;
	}else{
    
    
		return sum;
	}
	
} 

all codes

#include<stdio.h>

//10的n次方 
int g(int n){
    
    
	int t=1;
	int i;
	if(n==0){
    
    
		return 1;
	} else{
    
    
		for(i=0;i<n;i++){
    
    
			t=t*10;
		}
	}
	return t;
}

int f(char* s){
    
    
	int a[100];
	int top=-1;
	int i;
	int flag=0;//如果第一位是符号,则用flag记录 
	int sum=0;//记录最后的返回值 
	
	for(i=0;s[i]!='\0';i++){
    
    //遍历字符串s 
		if(s[i]=='-'||s[i]=='+'){
    
    //如果是符号则放入flag中 
			flag=s[0];
		}else{
    
    
			top++;
			a[top]=s[i]-48; //字符转整型减48 
		}
		
	}
	
	
	
	for(int i=0;i<=top;i++){
    
    //遍历整型数组a 
		sum=sum+a[i]*g(top-i);//每一项乘以对应的数量级 
		
	}
	
	if(flag==45){
    
    //判断符号 
		return -1*sum;
	}else{
    
    
		return sum;
	}
	
	
} 


int main(){
    
    
	char s[100];
	scanf("%s",s);
	int a=f(s);
	printf("%d",a);
} 

insufficient

If the integer array represented by the string exceeds the range that int can store, overflow will occur.

Guess you like

Origin blog.csdn.net/baiqi123456/article/details/123786981