C++怎么可以输出一个string类型的最后一个字符

C++语言 码拜 8年前 (2016-04-27) 2571次浏览
仔细看下面这段代码:
#include <iostream>
#include <fstream>
#include <math.h>
#include <string>
using namespace std;
int main()
{
string a[4]={“sfsdgf4″,”dsgr5″,”fgs3″,”rewgr3”};
long i,j,k,t;
double count=0;
for(k=0;k<4;)
{   j=a[k][a[k].length()-1];
for(i=0;i<j;i++)
{
count++;
cout<<count<<endl;
}
k++;
}
return 0;
}
本人的目的是输出string数组中每个string的最后一个字符之和的数,例如啊a[0]的最后一个字符是4,a[1]为5,a[2]为3, a[3]为3 ,本人想输出4+5+3+3个数字
解决方案

50

j=a[k][a[k].length()-1] 得到的是char型的字符,需要-“0″才能得到int型数据

#include <iostream>
#include <fstream>
#include <math.h>
#include <string>
using namespace std;
int main()
{
	string a[4]={"sfsdgf4","dsgr5","fgs3","rewgr3"};
	long i,j,k,t;
	double count=0;
	for(k=0;k<4;k++)
	{   
		j=a[k][a[k].length()-1] - "0";
		for(i=0;i<j;i++)
		{
			count++;
			cout<<count<<endl;
		}
	}
	return 0;
}

15

string a[4]={“sfsdgf4″,”dsgr5″,”fgs3″,”rewgr3”};
long j,k;
double count=0;
for(k=0;k<4;k++)
{   j=a[k][a[k].length()-1]-“0”;
cout<<“the string of the “<<k<<“st is:”<<j<<endl;
count+=j;
}
cout<<“the sum of the numbers is :”<<count<<endl;
return 0;
可以达到你的要求

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明C++怎么可以输出一个string类型的最后一个字符
喜欢 (1)
[1034331897@qq.com]
分享 (0)