Need help converting numbers into words

Hi, I am trying to read into a file that has something like

I have 5 apples and 9 bananas.
Sam has 8 apples and 6 bananas.

and I need to replace the numbers with words. For example I need to change the "5" to five and so on. The problem is that im not sure how to access and then replace just the numbers. Any help will be appreciated.

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
#include <iostream>
#include <cmath>
#include <fstream>
#include <cstdlib>
#include <iomanip>
using namespace std;



int main()
{
	
	ifstream in_stream;
	in_stream.open("input.dat");
		if(in_stream.fail())
		{
			cout<< "Input file opening failed.\n";
			exit(1);
		}

	string line[30]; // creates SIZE empty strings
	int i=0;
	while(!in_stream.eof()) {
	  getline(in_stream,line[i]); // read the next line into the next string
	  ++i;
	}
	int numLines = i;

	for (i=0; i < numLines; ++i) {
	  cout << i << ". " << line[i]<<endl; // no need to test for empty lines any more
	}
so what i got so far is
line[0].replace(line[0].find("4"), 1, "four");

it works. but is there a more efficient way so it can look for any number from 1-10 and replace it with its corresponding word.
First: never loop on EOF. It can cause problems, rather loop on the getline itself: while (getline(in_stream, line[i])) { ++i; }

Now, you can probably use a map or an array or something to store the various numbers and their word counterparts, and then test to see if it is a number and replace it with the value in the map. Here is an example (assuming only 1-digit numbers):
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 <iostream>
#include <string>
#include <fstream>

int main() {
    const std::string numbers[] = {
        "zero",
        "one",
        "two",
        ...
        "nine"
    };

    ...

    for (i = 0; i < numLines; ++i) {
        for (int num = 0; num < 10; ++num) {
            std::size_t pos = 0;
            if ((pos = line[i].find(std::to_string(num))) != std::string::npos) {
                line[i].replace(pos, 1, numbers[num]);
            }
        }
        std::cout << i+1 << ". " << line[i] << std::endl;
    }

    return 0;
}

http://ideone.com/rCuHyM
Last edited on
Topic archived. No new replies allowed.