Converting int value to English translation

Can you guys help me? I have this program for the most part figured out. But certain numbers are giving me trouble. If I enter 313 the output via this code will be (Three Hundred One Three). I need to display (Three Hundred Thirteen).
Can someone please explain? I am going wrong somewhere in NumbersPrint.cpp

main function source file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>
#include <iomanip>
#include "Numbers.h"
using namespace std;

int main()
{
	int NUM;
	cout << "This program translates a integer value into it's English Word equivalent." << endl;
	cout << "\nPlease enter an integer value (0-9999): ";
	cin >> NUM;

	while (NUM < 0 || NUM > 9999)
	{
		cout << "Invalid value!" << endl;
		cin.clear();
		cin.ignore();
		cin >> NUM;
	}

	Numbers test(NUM);
	test.print();

	return 0;


Numbers.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#ifndef NUMBERS_H
#define NUMBERS_H

class Numbers
{
private:
	int number;
public:
	Numbers(int num)
	{
		number = num;
	}
	void print();
};

#endif 


NumbersPrint.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
#include <string>
#include "Numbers.h"
using namespace std;

void Numbers::print()
{
	 string lessThanTwenty[20] = { " ", "One", "Two", "Three", "Four", "Five" ,"Six", "Seven", "Eight",
		"Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };

	 string tens[10] = { " ", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninty" };

	 string hundreds = " Hundred";

	 string thousands = " Thousand";

	// Residue holds what remains to be printed.
	int residue = number;

	// Take care of thousands, if any.
	int n_thousands = residue / 1000;
	residue = residue % 1000;
	if (n_thousands > 0)
	{
		cout << lessThanTwenty[n_thousands];
		cout << thousands;
	}

	// Fill the blank
	// Take care of hundreds, if any.
	int n_hundreds = residue / 100;
	residue = residue % 100;
	if (n_hundreds > 0)
	{
		cout << lessThanTwenty[n_hundreds];
		cout << hundreds;
	}

	// Take care numbers less than a 100.
	int n_tens = residue / 10;
	residue = residue % 10;
	if (n_tens > 0)
	{
		cout << " " << lessThanTwenty[n_tens];
	}

	// Take care of anything less than 20
	int n_ones = residue / 1;
	residue = residue % 1;
	if (n_ones > 0)
	{
		cout << " " << lessThanTwenty[n_ones];
	}
	cout << endl;
}
At line 39 you «Take care numbers less than a 100.». There, in your example, `residue' would be 13 and you should do something like
1
2
if (residue<20)
   std::cout << lessThanTwenty[residue] << '\n'; //no further processing 



By the way, you never use your `tens' array
Topic archived. No new replies allowed.