//chapter 4 ,ex 6 -the program will read the numbers from 0-9 into words and typing them out
#include <iostream>
#include <string>
#include <vector>
usingnamespace std;
int main()
{
int i =0;
string number="";
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 <<"Please enter a number between 0-9 with letters: ";
while (cin >> number){
for(i=0;i<11;++i){
if (number == numbers[i])
cout << i<<endl;
}
}
}
//chapter 4 ,ex 6 -the program will read the numbers from 0-9 into words and typing them out
#include <iostream>
#include <string>
#include <vector>
usingnamespace std;
int main()
{
int i =0;
string number="";
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 <<"Please enter a number between 0-9 with letters: ";
while (cin >> number){
for(i=0;i< numbers.size()-1;++i){ //I don`t have numbers[10] -thats the mistake
if (number == numbers[i])
cout << i<<endl;
}
}
}
You took the trouble to make sure that you used only numbers[0] to numbers[9] when entering the values,
yet when you make the check loop, your loop counter goes from 0 to 10. numbers[10] is an invalid index
int main()
{
int number = 0;
vector<string> numbers;
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 << "Number please: ";
while (cin >> number) //Not 100% sure about this way of doing it.
{
cout << numbers[number];
}
#ifdef DEBUG
//Pause using your favorite method.
#endif
}
I changed the data type of number to int so the user can type the integer as a number. The way you have it assumes the number will be typed as a string (i. e. seven as opposed to 7).
If the number as a string thing is a requirement, then go back to your inner for loop. But the vector numbers should have a method to find the string so you don't have to code the inner loop. Don't ask me how because I barely use STL (I know! For the nth time, shame on me! :-) ).
Thanks for pointing my mistake - i always forgot the vector starts from 0...
Ok the problem is solved - i was trying to test vector`s[10] when i don`t have such.