题目描述:
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
解题思路:
先遍历字符串把各位加起来(ch-'\0'),用变量sum存放结果
再把sum转化成字符串遍历
重点:
int类型转化成string类型:
方法一:
用stringstream:
stringstream使用原理:
使用stringstream对象s简化类型转换,它内部有一个string的流对象缓冲区,它会识别输入的变量(s<<右边的变量)的类型转换为string存储到内部的缓冲区内,然后当用它输出时,它会识别输出变量(s>>右边的变量)的类型,然后从流对象中转化到该类型赋值给这个对象。在每次用过一次之后要清除s里剩余的字符(s.str("");),然后因为输出一次它内部的一些位就失效了,因此还要clear一下(s.clear();),使用它就不必担心缓冲区溢出(sprintf会导致这个问题),因为s会根据需要自动分配存储空间。
————————————————
原文链接:https://blog.csdn.net/u012482828/article/details/72522677
方法二:
to_string函数:
包含于头文件<string>
定义于头文件
std::string to_string(int value); (1) (C++11起)
std::string to_string(long value); (2) (C++11起)
std::string to_string(long long value); (3) (C++11起)
std::string to_string(unsigned value); (4) (C++11起)
std::string to_string(unsigned long value); (5) (C++11起)
std::string to_string(unsigned long long value); (6) (C++11起)
std::string to_string(float value); (7) (C++11起)
std::string to_string(double value); (8) (C++11起)
std::string to_string(long double value); (9) (C++11起)
代码演示:
#include <bits/stdc++.h>
using namespace std;
void print(int num)
{
stringstream ss;
ss << num;
string str;
ss >> str;
int len = str.length();
for (int i = 0; i < len; i++)
{
char ch = str[i];
if (i != 0)
{
cout << " ";
}
switch (ch)
{
case '0':
{
cout << "zero";
break;
}
case '1':
{
cout << "one";
break;
}
case '2':
{
cout << "two";
break;
}
case '3':
{
cout << "three";
break;
}
case '4':
{
cout << "four";
break;
}
case '5':
{
cout << "five";
break;
}
case '6':
{
cout << "six";
break;
}
case '7':
{
cout << "seven";
break;
}
case '8':
{
cout << "eight";
break;
}
case '9':
{
cout << "nine";
break;
}
default:
break;
}
}
}
void trun(string str)
{
int sum = 0;
for (int i = 0; i < str.length(); i++)
{
char ch = str[i];
sum += (ch - '0');
}
print(sum);
}
int main()
{
string str;
cin >> str;
trun(str);
return 0;
}
提交结果截图: