Converting int to array

Pages: 12
Hi,

I'm trying to write a program that converts numbers to text.
Example:
14 = fourteen
1067 = one thousand sixty seven

Basically I'm trying to split the number into sets of 3 digits and adding hundreds/thousands etc while hard coding 1-19 and adding the strings together if that makes sense? But for that I need the number in an array so I can look at the different sets of numbers? like

1
2
3
if ((num>99) && (num<1000)){
  return under20(num[0])<<" hundred "<<under20(num[2, 3]; //under20 is a function return strings for each number
}


I really have no clue how to convert to an array but the book I'm learning from hasn't even covered arrays yet? So is there any easier way to do this?

Thanks for any help
You can use a string stream object for this.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <sstream>

std::stringstream sstream;

int main() {
	int number = 123;
	sstream << number;//read integer into stringstream object.
	std::string numberString = sstream.str();//assignment.

	std::cout << numberString << std::endl; //Print the entire string.
	for(unsigned i=0; i<numberString.size(); i++) {//Unnecessary loop just to demonstrate.
		std::cout << numberString[i];
	}
	std::cout << std::endl;

	sstream.str("");/*Don't forget to clear the stringstream object!
					If you don't clear it, any content you read into the stringstream will just append 
					to anything you've previously read.*/

	std::cin.sync();
	std::cin.get();
	return 0;
}
Thanks xismn, I'm having some trouble passing numberString to my functions though. I want to be able to pass say numberString[0], read the number and if its a 2 return the string "twenty". I'm having difficulty doing that... Heres my code so far

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
56
57
58
59
60
61
62
63
64
65
66
67
#include <iostream>
#include <sstream>

using namespace std;
stringstream sstream;

string under10(int num);
string teens(string numberString);

int main(){
	int num;
	cout<<"Please enter a number: ";
	cin>>num;
	sstream<<num;
	string numberString = sstream.str();
	
	if (num<10){
		cout<<under10(num);
	} else if ((num>9) && (num<20)){
		cout<<teens(numberString[0])<<" "<<under10(num);
	}
}

string under10(int num){
	if (num==1){
		return "one";
	} else if (num==2){
		return "two";
	} else if (num==3){
		return "three";
	} else if (num==4){
		return "four";
	} else if (num==5){
		return "five";
	} else if (num==6){
		return "six";
	} else if (num==7){
		return "seven";
	} else if (num==8){
		return "eight";
	} else if (num==9){
		return "nine";
	}
}

string teens(string numberString){
	if (numberString[0]="1"){
		return "ten";
	} else if (numberString[0]==2){
		return "twenty";
	} else if (numberString[0]==3){
		return "thirty";
	} else if (numberString[0]==4){
		return "fourty";
	} else if (numberString[0]==5){
		return "fifty";
	} else if (numberString[0]==6){
		return "sixty";
	} else if (numberString[0]==7){
		return "seventy";
	} else if (numberString[0]==8){
		return "eighty";
	} else if (numberString[0]==9){
		return "ninety";
	}
	return 0;
}


Thanks
Hi,
when you say
I want to be able to pass say numberString[0], read the number and if its a 2 return the string "twenty".
do you mean numberString holds a set of 'numbers', and (thinking of a string as an array of characters) each index represents a power of 10? If not, that may be a good way to look at it. Of course the numbers would be backwards compared to our normal way of interpreting base10, but your program and the computer wouldn't care.
Hey,

Sorry I'm a little lost, I want to be able to type a number into the console, and have it output the number in words. The book I am learning from suggests breaking the number down into groups of 3 digits, and working out the hundreds tens and ones, then if the number is bigger just add all the sets of 3 digit words together if that makes sense?

I thought about arrays as I would need to look at the different places of the number, or what xisnm has shown, but the book hasn't even covered arrays yet and has been pretty simple up until now. This question has really thrown me. But then if I look at numberString[1], will the number get returned or ??

I'm so tempted to skip this question but I feel I'm missing some important lesson here.
This is a great question to be asked, and is possible without knowing about arrays explicitly. However basic knowledge of arrays could help you in solving this problem simply.

After reading your latest post, I think I have a better idea of what you're looking for. I'll cover arrays briefly to give you an idea of what is going on with them, and you can decide if you want my help in implementing an array-based solution.

Arrays are nothing more than a series of variables stored sequentially in data memory. An array's elements are all of the same type, so declaring an array of type int will make all elements of that array ints, an array of type char will be an array where each element is type char. The name of the array is a variable itself and is actually a pointer to the very first element in memory, and each element comes after. In terms of an int, which takes up 4 bytes of memory, each element of the array would appear individually as a chunk of 4 bytes, one after another.

An element is an individual piece of an array...for a moment think of an array as a line of fruit. An array of fruit can only have fruits of ALL the same type, for instance oranges. An array of oranges, in our example orange is the data type just like int or char would be. Each consecutive element's position is numbered by something called an index, and that element can be directly accessed via its index. It's called dereferencing, and is a clever way to access the nth element via the original pointer, pointing to the beginning of the array in memory.

SO...if you're still awake and interested...
The first element is actually index = 0. You can think of the index as the number of oranges that the current orange in question is from the first orange (or element). The nth element's index is actually [n - 1]...

Here are some examples to show you how it looks in code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int x; // Dummy storage variable for this example
int my_array[10]; // This is an integer array with ELEVEN elements.

// To access my_array's 5th element, the code would be as follows.

x = my_array[4]; // Remember element 1 is at my_array[0], count up and
				 // the 5th element appears at my_array[4].

// Values can be assigned to arrays by:
my_array[0] = 6;	// 1st element, at index 0, is now 6
my_array[1] = 2;
my_array[2] = 4;

// You can also step through an array with a loop!!

// Assuming each element in the array has some value
for (int i = 0; i < 11; i++)
{
	cout << "my_array[" << i << "] = " << my_array[i] << endl;
}


I can understand if you'd rather wait to get more experience with arrays, or would rather just use a string/char stream for this problem. Regardless, hopefully you got something from this assault of text. If it's your first time learning specifically about arrays, it may be a bit to take at once. Let me know :)

Cheers!
Last edited on
Thanks so much for taking the time out to help me, I did learn a little about arrays a while ago just trying to remember how they work. I've never used the sstream before so I think it would be easier for me with arrays, but could I just read the number straight into an array? Or do I have to read it in as an int and then transfer it to an array as this is what I had thought and am having difficulties with.

Also if I can just read it straight into an array like

1
2
3
int myNumber[]; //how do I set up the array if I do not know how long the number is going to be that.s entered?
cout<<"Enter a number: ";
cin>>myNumber[]; 


Also when passing an array to a function, do I need the [] brackets?

1
2
3
int tens(int myNumber[]){
 code
}


Any number under 20 is fine because its coded in, but if the number was 124, I need to look at the num[0] and call under10 function to print out "one" then look at num[1] and call tens function to print "twenty" then the num[2] and call ones to print "four", then add them all together.. Is this is best way ? I cant get my int num transfered to an array of ints though..

Sorry for all these questions, I just cant believe how straight forward chapter 6 was, started chapter 7 today and its a big jump up lol..
Last edited on
No worries about the questions! Ask, and I'll do my best to answer.

could I just read the number straight into an array?
If you read the number as a string, a string behaves like an array, and for most purposes can be treated as one. It's basically a special array defined as a class with certain methods and such as you would expect as class to have. More on this in text and links below. . .

Also if I can just read it straight into an array like

1
2
3
int myNumber[]; //how do I set up the array if I do not know how long the number is going to be that.s entered?
cout<<"Enter a number: ";
cin>>myNumber[]; 


You would declare myNumber as a string variable instead. No need of the brackets either. The concept of arrays is parallel in a lot of ways to strings, which is why I made sure you knew some of the basics. Just make sure you use the right include's to support the string code though. Also, if you don't know how long the number is going to be that's entered, this raises more questions. You could ask the user...but that's not very streamlined. You could hard-code it...but that's poor design. If you're interested in making your code more robust you could implement a vector for this purpose. A vector is a dynamic array, which basically just means you can resize it after declaring it at as another size. Maybe you could think of a clever way to poll the size of the incoming string and adjust the vector size accordingly? There are many possibilities.

Also when passing an array to a function, do I need the [] brackets?
1
2
3
int tens(int myNumber[]){
 code
}

The brackets are unnecessary...and in fact will cause errors. The compiler is 'smart enough' to know that myNumber is an integer array (as long as you declared it as such!), or more specifically a pointer to an integer array. Passing in an array allows you to access and alter the elements in it. A correct implementation of the code in question would be:
1
2
3
4
5
6
7
int tens(int myNumber)
{
	// Code
}

// The compiler will look for what myNumber is
// during the compilation process. 


As extra homework and learning potential (which will help you in this program), check out these articles here on cplusplus.com. I'll select particular notes of interest for your current application. Hopefully it will give you a good idea of how you might want to use your knowledge of arrays to your advantage.


http://www.cplusplus.com/doc/tutorial/ntcs/
Double quoted strings (") are literal constants whose type is in fact a null-terminated array of characters.


http://www.cplusplus.com/reference/cstring/strtok/
A sequence of calls to this function split str into tokens, which are sequences of contiguous characters separated by any of the characters that are part of delimiters.

Note on delimiters from the above article: An example of a delimiter for your use could be a comma. Anything to the left of that comma in your input string is a digit that is greater than 999, like the number 1,134. The comma can be used as a delimiter to know where increments of 1e3 (like 10^3, 10*10*10, 1000, you get the point) occur, and thus separate fields of digits that represent thousands, millions, you name it.

As for parsing the individual digits of ones, tens and hundreds, I'll have to take some time to think about it and point you in a good direction that seems intuitive. I've gotta go to bed to get up for work though, so maybe I'll do some research and add to this thread at lunch or something :)
Last edited on
Wow, thanks man, kinda lost me towards the end though lol.

I think if I just read the number in as a string will be easiest if I can still look at each element with number[i]. I changed my program over but now it is not reading any number between 1-19 which was working before as they were just coded in.

I have a if statement to call a function for the ones like

1
2
3
if (num<"10"){
 call function
}


But because its a string it doesn't read 10 as a number does it? I tried looking up the ascii character for 10 and I found 57 for nine, so i tried swapping the 10 for 57 but still no luck.. However, I keep it at 57, and enter a number under 4 it works?

I'm so confused -_-

EDIT: Never mind, I found out that the ascii code for 10 you need to add 1(49) and 0(48) giving 97. I swapped the 10 for 97 and BOOM. :)

EDIT EDIT: Ok, thinking I could just use

1
2
3
if ((num>="97") && (num<="106"){
 call function
}


for numbers 10-19, sadly it didn't work.. It runs without error but I get a weird error message in the console saying terminate or something. So instead of doing the check above can I somehow do

1
2
3
4
if (num.size()>2)
 call functiontens(num[0])
 call functionones(num[1])
 cout text


Last edited on
You can pursue this in the strategy that you are using, but make sure you realize the power of interpretting a string as an array of characters. A string as an array has each element as a separate character from that string. The characters in the string each have a corresponding array index depending on the order in which they appear in the string.

Here's an example that I just threw together and tested to demonstrate this point. Side note: Keep in mind that I learned with C and may have some "bad" habits when it comes to sticking to C++ practices...I tend to use
C-based strategies or C code while utilizing some of the benefits of C++ when I see fit. But again that is probably based on habit and the way I learned programming. C++ was developed as "C with classes", so most of C++ utilizes the same functionality as C.

Now on to the example. . .
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
#include <string>
#include <iostream>
using namespace std;

int main ()
{
	// Initialize a string
	string myNum;
	myNum = "1234"; // myNum now has the string "1234" stored in it

	// Print out each character in myNum
	cout << "myNum[0]: " << myNum[0] << endl;
	cout << "myNum[1]: " << myNum[1] << endl;
	cout << "myNum[2]: " << myNum[2] << endl;
	cout << "myNum[3]: " << myNum[3] << endl << endl;
	
	// Using the std::string class and capitalizing on objects...
	int my_size; // Initialize variable to store the string's size

	my_size = myNum.size();   // Use the .size() method, which returns the size of the string,
			          // not counting the null-character
	cout << "my_size = " << my_size << endl;

	system("pause");

	return 0;
}


This simple main function is all you need to get a basic idea of storing a string, and then getting data from it, character-by-character.

This code produces the output:

1
2
3
4
5
6
7
8
9
10
11
 myNum[0]: 1
 myNum[1]: 2
 myNum[2]: 3
 myNum[3]: 4

 my_size = 4

// Note the array indexes 0 - 3 actually confirm the concept
// of an nth element having index = [n - 1]. Size is 4, but
// the 4th element has index 3. (Hopefully I'm not beating this
// concept into the ground) 


I think this idea will help in grabbing individual numbers, but there still lies an issue with knowing what power of 10 your digit represents...but wait! You know the index of each element! To save you some time, here's what I might do:

- Don't have the user include commas in their input to your program. For your purposes it might be better to focus on the process itself, and when you become more familiar with strings and arrays there are some cool tricks you could employ if you want to come back. I think you said previously there was something in the book you were learning from about employing the use of the commas or digit positions. This solution idea still uses digit positions, but in a different way. You can decide how you want to use this information.

- You're probably thinking "Oh it's all well and good knowing the index of the characters in the string, but how will that help me with getting digits and interpreting the actual number they represent??!"
The answer is quite simple actually. Think in terms of foundationally what our number system is, and particularly what each digit in a number actually represent.

This relates to my original comment that may have confused you and started this whole back-and-forth discussion. Our number system is decimal. Which means each position in which a number can reside represents a power of 10. Any number in that position is then multiplied by that power of 10 to get back the actual number that the position represents.

Think of it this way...you have the number 122. What is this number actually? It is one 100, two 10's and two 2's all added together.

122 = (1 * 100) + (2 * 10) + (2 * 1) = 100 + 20 + 2
This idea is SO much easier understand with drawings and an in-person discussion, but I think you get the point.

One position to the left of the decimal place is the 0th position. Ten to the power of zero, 10^0, is 1. Hence the one's place, and any digit in that position (2 in our example) becomes the value of simply 2. For the second position, or the ten's place, at index = 1, it is 2 * (10^1), which is 2*10 = 20. Your strings in your program have characters that represent digits, that are in certain digit positions, and have a unique index assigned to each character. Are you starting to see the power that arrays may have in this situation?? :)

Think through that a bit more, maybe try to look things up on it. Lessons on converting binary may help as well. Looking at numbers like this for Binary or Decimal are both fundamentally the same idea, but binary is base 2 instead of base 10. Numbers being represented by a sum of its digits and their position representing a power remains the same.

This is getting REALLY long, but I've still only hinted of how to implement this for your program. There's a lot of foundation for this idea though. Think indexes. You now have some user-input number as a string and need to determine each digit's value as an individual number. Arrays can be traversed backwards simply by using the index and the string's length or size methods to start from the end, but in our case the end of the string is actually the beginning (or the one's place). I would try maybe implementing some code in addition to practicing and understanding my previously posted code in this post.

Start with something like:
cout << "myNum[my_size - 1] = " << myNum[my_size - 1] << endl;
You should find that this expression results in displaying the last element, remembering that the last element is NOT at myNum[my_size] but at [my_size - 1], and thus the one's place of the current string we're working with. Hopefully this gives you more to work on and I didn't simply confuse you more. Read this multiple times and try to let it sink in, as well as coding, writing things down, drawing things...sometimes it takes a bit of thought to apply new concepts like these to difficult problems. :)

**EDIT: Oh! And there are SO many ways to do this...someone's probably going to get on here and be like "do this, and then that and you're done. This ENIGMA guy is trying to teach you quantum mechanics while making ice cream from scratch..." or something.

I figured this was a cool time to learn a bit of stuff about how and why certain things work. This isn't just info to help you solve only this problem, but start you learning and thinking about how these concepts can shape you as a problem solver. If you'd rather do this the easy way and you feel that I'm wasting your time, let me know.
Last edited on
Cheers dude, I was never expecting someone to take this much time out their life to try and help me understand this. You have provided me with more than enough info. I'm going to sit down over the next couple of days and try to get this program finish with the info from your last post.

Thanks again man Ill let you know how it ends up. :)
Awesome :) Glad to hear it.

I recently edited the above post to have some more clarity in those blocks of text.

It's a good day when I'm able to help someone. Good luck and I look forward to hearing about your progress.
Last edited on
The brackets are unnecessary...and in fact will cause errors. The compiler is 'smart enough' to know that myNumber is an integer array (as long as you declared it as such!), or more specifically a pointer to an integer array. Passing in an array allows you to access and alter the elements in it. A correct implementation of the code in question would be:


If you want a function to take an "array" the brackets, in fact, are required in the sense that something is required for the compiler to realize you want to pass the function a pointer. The name of the parameter is arbitrary. No other variables (of the same name or otherwise) are considered when determining the type of the parameter. Finally, that was not a correct implementation of the code in question (in fact, it wasn't an implementation at all.)

The following should give you some idea what's involved:

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
#include <iostream>
#include <string>

std::string digits[] = { "zero", "one", "two", "three", "four", 
                         "five", "six", "seven", "eight", "nine", "ten", 
                         "eleven", "twelve", "thirteen", "fourteen", "fifteen", 
                         "sixteen", "seventeen", "eighteen", "nineteen" } ;

std::string tens[] = { "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" } ;

std::string to_string(unsigned val)
{
    if ( val < 20 )
        return digits[val] ;

    return tens[(val/10)-1] + (val%10 == 0 ? "" : '-' + digits[val%10]) ;
}

int main()
{
    std::cout << "Enter a positive number that is less than 100.\n" ;
    unsigned value ;
    
    while ( std::cin >> value )
        std::cout << to_string(value) << '\n' ;
}

Thanks cire, I never thought of having the text in an array, but can you explain line 16 a bit more in depth? So you are calling the tens array with a value 32, so 32/10=3 -1 is 2 which gives you tens[2] which is the thirty if I'm correct?

And I get the digits[val%10] which is 32/10 r 2 but wouldn't that call digits[2] which is "one"? And I don't understand the (val%10==10?"":'-' bit.

Also I tried making it possible to enter a number upto 1000 with the following code, it doesn't produce any errors but when I type in a number the program crashes..

1
2
3
4
5
6
7
8
9
10
11
string to_string(int val){
    if ( val < 20 ){
		return digits[val] ;
	 } else if (( val > 19 ) && ( val < 100)){
		return tens[(val/10)-1] + (val%10 == 0 ? "" : ' ' + digits[val%10]) ;
	 } else if (( val > 99 ) && ( val < 1000)){
		return digits[val/100] + hundred + tens[(val/10)-1] + (val%10 == 0 ? "" : ' ' + digits[val%10]) ;  
                  //hundred is just a string I made to output the word "hundred"
	 }		 
	 return 0;
}


I thought that would be ok but obv not..
Cheers
Last edited on
And I get the digits[val%10] which is 32/10 r 2 but wouldn't that call digits[2] which is "one"? And I don't understand the (val%10==10?"":'-' bit.


The index for the first element of digits is 0, just like for all arrays, so digits[2] is the 3rd element in the array which is "two".

(val%10 == 0 ? "" : '-' + digits[val%10])

val % 10 == 0 is true when val is evenly divisible by 10. When that is the case, we don't want to add anything else to the string, but the nature of the ternary operator ?: is such that we the second term needs to evaluate to the same type as the third term, so in the case that val is evenly divisible by 10, we just add an empty string ("").

In the case where val is not evenly divisible by 10, we need to add a string "-x" where x is the textual representation for the 1's digit.

It could've been written:

1
2
3
4
5
6
7
8
9
10
11
12
std::string to_string(unsigned val)
{
    if ( val < 20 )
        return digits[val] ;

    std::string result(tens[(val/10)-1]) ;

    if ( val % 10 )
        result += '-' + digits[val%10] ;

    return result ;
}
Oh ok, Thanks for clearing that up, so what's wrong with my line 7 then? All I did was add a extra call to the digits function for the hundreds..

So if 932 was typed in, digits[val/100] = digits[9] which should output "nine" and then the tens and digits again?

I can't see why that's not working, I tried it without the hundred string in the middle aswel but it still crashes?
bump?
Have you seen this?
http://www.cplusplus.com/forum/lounge/74394/

[edit] Unless you are doing a homework assignment, check it out. :O)
Last edited on
Why does your to_string function end with return 0;?

I strongly suggest changing the name of to_string if you're going to bring std into the global namespace via a using directive, since std::to_string already has an implementation in C++11 and confusing the two is probably not something you want to do.

You didn't correctly account for the 10's digit in your code.

return digits[val/100] + ' ' + hundred + ' ' + tens[((val%100)/10)-1] + (val%10 == 0 ? "" : ' ' + digits[val%10]) ;

Notice that it still doesn't handle the case right for numbers in the teens (119) for instance.



Its not a homework assignment, I actually did C++ for half a year last year but took a break, am going back to it in a few months and trying to refresh my memory before I start.

What are the draw backs of using namespace std at the start of my programs? Because I was always told to do that but then again I did only do about 6 months programming.

And thanks ill add another if statement in to handle the teen numbers.

Also should I replace the return 0 with an exit 0;? Because If I leave nothing there I am getting a warming that it reaches the end of a non void function. But I cant see how because it's not reaching the end its returning the string?

EDIT: Cheers for everyone that helped me here, its not complete yet but going to come back to it at a later date. Gone onto next chapter and it's much easier, I'm really not sure why this chapter was so hard, maybe because the chapter is called What to do when you cant figure out what to do... lol. Ill come back to it once I'm further through the book and covered arrays etc.

Thanks again.
Last edited on
Pages: 12