1005 Spell It Right (简单题&&数字转字符串)

1005 Spell It Right (20)(20 分)

Given a non-negative integer N, your task is to compute the sum of all the digits of N, and output every digit of the sum in English.

Input Specification:

Each input file contains one test case. Each case occupies one line which contains an N (<= 10^100^).

Output Specification:

For each test case, output in one line the digits of the sum in English words. There must be one space between two consecutive words, but no extra space at the end of a line.

Sample Input:

12345

Sample Output:

one five

【分析】核心就是数字与字符串的转换

/*数字转字符串*/
int x=123;
stringstream sstr << x;
string str = sstr.str();
cout<<str<<endl;        //此时str=“123”

/*字符串转数字*/
string str = "123";
stringstream sstr(str);
int x;
sstr>>x;    //x为整数123

【代码】

#include<bits/stdc++.h> 
using namespace std;
char s[105];
int main()
{
   while(~scanf("%s",s))
   {
   	int len=strlen(s);
   	int sum=0;
   	for(int i=0;i<len;i++)
   		sum+=s[i]-'0';
   	stringstream sstr;
   	sstr<<sum;
   	string str=sstr.str();//cout<<str<<endl;
   	int l=str.length();
   	for(int i=0;i<l;i++)
   	{
   		if(i)cout<<" ";
   		if(str[i]=='0')cout<<"zero";	
   		if(str[i]=='1')cout<<"one";
   		if(str[i]=='2')cout<<"two";	
   		if(str[i]=='3')cout<<"three";
   		if(str[i]=='4')cout<<"four";	
   		if(str[i]=='5')cout<<"five";
   		if(str[i]=='6')cout<<"six";	
   		if(str[i]=='7')cout<<"seven";
   		if(str[i]=='8')cout<<"eight";	
   		if(str[i]=='9')cout<<"nine";
	}
	cout<<endl;
   }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38735931/article/details/81625416