Input check on a while loop?

Hello, this is an exercise from the book i am using to learn c++ at the moment and i found this same exercise on an older post here but no one did it like me and i wander if there is any way i can make both conversions work depending on the input, i can only make them work separately right now.

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. 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.



int main()
{
#include "../../../std_lib_facilities.h" //the book's header

int num=0;
string spelling="";
vector <string> numbers(10);
numbers[0]="zero";
numbers[1]="one";
numbers[2]="two";
numbers[3]="three";
numbers[4]="four";
numbers[5]="five";
numbers[6]="six";
numbers[7]="seven";
numbers[8]="eight";
numbers[9]="nine";
cout<<"Enter a digit from 0 to 9 to print it's spelling on the screen"<<endl;
while (cin>>spelling||cin>>num)
{
if (spelling=="") cout<<numbers[num]<<endl;//not sure about this
else
{
for(int i=0; i<10; i++)
{
if (spelling==numbers[i]) cout<<i<<endl;
}
}

}
system("pause");
}
Sorry I didn't understand how the formats work here yet..
Last edited on
To give you a quick idea...

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

int main()
{
    std::vector <std::string> numbers {"Zero", "One", "Two", "Three", "Four", "Five",
	   "Six","Seven","Eight", "Nine"};

    bool keepLooping{ true };

    std::cout << "Enter a digit from 0 to 9 to print it's spelling on the screen Or\n";
    std::cout << "Enter a spelled-out number from Zero to Nine to print\n";
    std::cout <<"the digit on the screen\n";

    while (keepLooping)
    {
	   int num{ 0 };
	   while (std::cin >> num)
	   {
		  if (std::cin.good())
			 std::cout << numbers[num] << std::endl;

		  else
			 break;
	   }

	   std::cin.clear();
	   std::string spelledNumber{ "" };
	   if (std::cin >> spelledNumber)
	   {
		  for (int count = 0; count < 10; count++)
		  {
			 if (spelledNumber == numbers[count])
				std::cout << count << std::endl;
		  }
	   }
    }
    return 0;
}


Sample Ouput:
Enter a digit from 0 to 9 to print it's spelling on the screen Or
Enter a spelled-out number from Zero to Nine to print
the digit on the screen
4
Four
Nine
9
5
Five
6
Six
Six
6
Seven
7
Thank you very much, so cin.good() was the check i was looking for and the second while seems to be a good idea.
Topic archived. No new replies allowed.