Currently working on an exercise from Stroustrup's intro to C++ book and it asks: Write a function that given two vectors price and weight computes a value (an “index”) that is the sum of all price[i]*weight[i]. Make sure to have weight.size()==price.size()
vector<double> weight;
vector<double> price;
void read_weight() {
cout << "Input weight" << '\n';
for (double weights; cin >> weights; ) {
weight.push_back(weights);
if (!(cin >> weights)) {
cin.clear();
cin.ignore(numeric_limits<double>::max(), '\n' );
break;
}
}
}
void read_price() {
cout << "Input price" << '\n';
for (double prices; cin >> prices; ) {
price.push_back(prices);
if (!( cin >> prices)) {
cin.clear();
cin.ignore( numeric_limits<double>::max(), '\n' );
break;
}
}
}
void calculate() {
double sum = 0;
for (int i = 0; i < price.size(); ++i)
sum += price[i] * weight[i];
cout << "Sum is " << sum << '\n';
}
int main() {
read_weight();
read_price();
calculate();
}
This is the code I currently have, but I cannot figure out how to terminate input properly. In previous chapters, his book mentions you could use an input besides a double to terminate (like |). However, I learned that this only puts cin into the failed state and does not allow me to move onto the price function. Unfortunately, the book does not cover how to handle this as of yet so I just copied code about cin.clear and cin.ignore in hopes that it would work. But this did nothing. I noticed that I was actually allowed a single input if I were to change the vector to int instead of double and am perplexed for the difference in behavior. I was wondering if anyone could give me tips on how to fix this?
Aucun commentaire:
Enregistrer un commentaire