I want to create the program, that coverts number into digits written by words.
Example: n = 1321 -> output: "one"-'three"-"two"-"one"
Here is my code:
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int digits(int number){
int digits = 0;
while (number != 0){number /= 10; digits++;}
return digits;
}
int main(){
int num,remainder,i;
int digits(int);
vector<string> num_str = {"zero","one","two","three","four","five","six","seven","eight","nine"};
cin >> num;
int length = digits(num);
vector<int> num_int(length);
while(num > 0){
remainder = num % 10;
num_int.push_back(remainder);
num /= 10;
}
for(i = 0;i<num_int.size();++i){
if(i == (num_int.size() - 1)){
cout << num_str[num_int[i]];
}else{
cout << num_str[num_int[i]] <<"-";
}
}
return 0;
}
For example I enter:43 and I got output: "zero-zero-four-three". And the number of "zero" is always equal to number of digits in number. How can I fix it?
Does it have to have 'digits' extraction the way you did it or do you want just to print numbers as strings?
#include <iostream>
#include <string>
int main()
{
std::string const nums[10] = { "zero","one","two","three","four","five","six","seven","eight","nine" };
long long num;
std::cin >> num;
std::string const numStr = std::to_string(num);
for (size_t i = 0; i < numStr.length(); ++i)
std::cout << (i > 0 ? "-" : "") << "\"" << nums[numStr[i] - 48] << "\"";
std::cout << std::endl;
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.