In all these exercises I am using Visual Studio Community 2015 and the header file "std_lib_facilities.h" which can be found here:
http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h
My version is spelt differently so adjust the code accordingly if copying and pasting.
Chapter 4 Exercise // 4.6
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 program, using the same input loop,convert spelled-out numbers into their digit form: e.g., the input seven gives the output 7.
#include "stdafx.h"
#include "std_lib_facilities_new_version.h"
using namespace std;
int main()
{
vector<string> values1{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
vector<string> values2{ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
char loop = 'y';
cout << "This program spells out digits or converts them.\n";
while (loop == 'y')
{
cout << "Please enter a digit between 0 - 9 to spell out or write a digit to convert to a number: \n";
string digit;
cin >> digit;
for (int i = 0; i < values1.size(); ++i)
{
if (digit == values1[i])
{
cout << values2[i] << endl;
}
else if (values2[i] == digit)
{
cout << values1[i] << endl;
}
}
cout << "Would you like to continue? y / n \n";
cin >> loop;
}
keep_window_open();
return 0;
}
This one was extremely annoying mainly because my IDE kept throwing fits during the for loop when I had originally initialised my vector like this:
vector<string> values1(10);
(then assigned something to each value in values1)
Since I am still teaching myself I have no idea why it kept throwing this fit, and the internet didn't help. However when I changed it how it is above, it worked perfectly. If someone could explain to me in dunce terms why that didn't work, it would be greatly appreciated.
I'm also not sure if he meant for us to use two vectors or not. But at this moment in time, I'm not sure how to do this without using two vectors because you can't compare a string to an int and vice versa.
No comments:
Post a Comment