Subscript out of range error

Good afternoon everybody, I've been trying to made converter of values entered.
Basic idea is to make converter which converts a lot of values different units.
But it prints out and converts only last value I've entered, and in the end I'm getting error : Vector subscript out of range.



#include "stdafx.h"
#include "iostream"
#include "vector"
#include "string"
using namespace std;

int main()
{
vector <double> values;
vector <string> units;
double value = 0;
string unit;
for(int x =0; x<100; x++) /*for loop made to read input into value and unit, then push it into vectors and
to print out the result */
cin >> value >> unit;
values.push_back(value);
units.push_back(unit);
if (unit == "m")
cout << value / 100 << "m" << '\n';
else if (unit == "cm")
cout << value * 100 << "cm" << '\n';
else if (unit == "in")
cout << value *2.54 << "cm" << '\n';
else if (unit == "ft")
cout << value * 12 << "in" << '\n';
else
cout << "I don't know this unit" << '\n';

//here I'm trying to print out all the values entered
for (int x = 0; x < 100; x++) {
cout << values[x] << endl;
cout << units[x] << endl;
}

return 0;

}
Your first for loop contains one line only:
cin >> value >> unit;
So you add precisely one value to the values vector, and one to the units vector.



Thank you for the answer! Now I do understand the error! But how could I create loop which contains more than one line?
Last edited on
Here's an example of a loop containing two lines:

1
2
3
4
for (int x = 0; x < 100; x++) {
cout << values[x] << endl;
cout << units[x] << endl;
}
Thank you! Now it really works! Have a nice day =)
Topic archived. No new replies allowed.