C++ - 从字符串中提取一个数的若干种写法

提取整数

要求:输入一个字符串里面包含一个整数,注意字符串中可能有空格。

用字符串string

image

用char

image

提取整数

要求:输入一串字符串,里面包含若干个小数,字符串中可能有空格。

比如输入:The marathon runner completed the 10.5-kilometer race in under an hour, averaging a pace of 4.75 minutes per kilometer.;

遍历后转数值的写法

string s="The marathon runner completed the \
10.5-kilometer race in under an hour, \
averaging a pace of 4.75 minutes per kilometer."; 

//获取每一个数值 
double num=0,xsw=0.1;
bool xs=false;
for(int i=0;i<s.size();++i){
	if(s[i]>='0' && s[i]<='9'){
		int c=s[i]-'0';
		if(xs==false){
			num=num*10+c;
		}
		else{
			num+=c*xsw;
			xsw/=10;
		}
	}
	else if(s[i]=='.'){
		xs=true;
	}
	else{
		if(num!=0){
			cout<<num<<endl;
			num=0;
		}
		xs=false;
		xsw=0.1;
	}
}

用stod

string s="The marathon runner completed the \
10.5-kilometer race in under an hour, \
averaging a pace of 4.75 minutes per kilometer."; 

string cn="";
for(int i=0;i<s.size();++i){
	if(s[i]>='0' && s[i]<='9' || s[i]=='.'){
		cn+=s[i];
	}
	else{
		if(cn.size()>0){
			cout<<stod(cn)<<endl;
			cn="";
		}
	}
}
posted @ 2025-10-12 10:40  一亩食堂  阅读(66)  评论(0)    收藏  举报