How to perform these 2 actions in one for-loop?

Hello, I am working through 'Programming: Principles and Practice Using C++' and have found myself stuck on exercise 6 of chapter 4. The first part of the exercise is:


Make a vector holding the ten string values "zero", "one", ... "nine". Use that in a program that converts a digit to its corresponding spelled-out value; e.g., the input 7 gives the output seven.


This part was easy.

1
2
3
4
5
6
7
8
    vector <string> nums = {"zero", "one", "two", "three", "four",
                            "five", "six", "seven", "eight", "nine"};
    
    cout << "enter a number 0-9: \n";

    for (int number; cin >> number;){
        cout << nums[number] << '\n';
    }


Where I struggle is on the second part of the question, which reads:


Have the same program, using the same input loop, convert spelled-out numbers into their digit form; e.g., the input seven gives the output 7.


I cannot wrap my head around how to do these within the same loop. I'd like to do it using only what I've learned so far, which isn't a whole lot - this is only chapter 4.

I figure I must change 'number' to type string, so it can accept either "seven" or "7" all in one loop. However, now this restricts me from using my earlier line, as doing something like:

 
cout << nums[int(number)] << '\n';


when I receive "7" does not work, and this is the only type-converting construct I've learned so far. I'm also not sure how to differentiate between if the user enters "7" or "seven" - normally I would think to check the size of the string, but I haven't been taught this.

As for receiving "seven" and trying to output 7, I haven't come across something which allows me to find the index of an element in a vector when I know the element, I've only learned to find the element using an index. Here I think I could iterate through the vector with a loop, incrementing a variable each time, then outputting that variable when we reach "seven".

How could I complete it for going from "7" to "seven"? As well as, how could I differentiate between digit vs spelled-out ("7" vs "seven") so that both lines do not execute for one input?

Not looking for code, rather for someone to point me in the right direction so I can try to work the rest out myself. Any help is much appreciated. Thanks guys

Last edited on
Ask the person each loop whether they want to convert from a number to a string or from a string to a number, then either cin and string or a number. Then start writing the code to convert a number to a string in the new if statement.
Topic archived. No new replies allowed.