甲级1005 Spell It Right

1005 Spell It Right (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 (10100​​).

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


分析:先按字符读入,每次读入都将该字符与'0'相减,然后得到sum。将sum输入到字符串流中,再用这个字符串流当作字符输出,输出来的字符再转为最后结果
这里sum的处理也可以用to_string(要包含<string>头文件),然后遍历这个字符串形式的sum,转成结果。
这里在输入的地方遇到了一个坑,如果用while (scanf("%c",&char_in) != EOF)来读取输入,就会报一堆错,大概是因为在输入的末尾不一定直接是EOF,也有可能是换行啊什么的


两份代码如下:

1、使用了字符串流的
 1 #include <iostream>
 2 #include <sstream>
 3 using namespace std;
 4 
 5 string digit[10]= { "zero","one","two","three","four","five",
 6                     "six","seven","eight","nine" };
 7 
 8 int main()
 9 {
10     string input;
11     char char_in;
12     int sum = 0;
13     cin >> input;
14     for (auto it = input.begin(); it != input.end(); it++)
15     {
16         sum += *it - '0';
17     }
18     stringstream ss;
19     ss << sum;
20     bool flag = false;
21     while (ss >> char_in)
22     {
23         if (flag == false)    flag = true;
24         else cout << " ";
25         cout << digit[char_in - '0'];
26     }
27     return 0;
28 }

 

 

 

 2、使用to_string的
 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 
 5 string digit[10]= { "zero","one","two","three","four","five",
 6                     "six","seven","eight","nine" };
 7 
 8 int main()
 9 {
10     string input;
11     int sum = 0;
12     cin >> input;
13     for (auto it = input.begin(); it != input.end(); it++)
14     {
15         sum += *it - '0';
16     }
17     string sum_str = to_string(sum);
18     bool flag = false;
19     for (auto it = sum_str.begin(); it != sum_str.end(); it++)
20     {
21         if (flag == false)    flag = true;
22         else cout << " ";
23         cout << digit[*it - '0'];
24     }
25     return 0;
26 }

 

 
posted @ 2019-01-19 10:24  囧YY  阅读(93)  评论(0编辑  收藏  举报