Reputation: 1
I have a program that takes in 10 "purchase prices" from a user and displays them in the console screen. I am attempting to modify the code to make it to where the user can determine how many inputs they like for "purchase prices" and then displays that amount of them on the console screen.
The current modification i was successful in was changing was the for loop inside the vector from for "(int i = 0; i < 10; i++)" to "for (int i = 0; i < purchases.size(); i++)" but from here I am stuck.
It seems that I may need some function or loop prior to the vector declaration to set the size variable based on user entries possibly but I am not sure. Thank you for you help-
My code:
vector<double> purchases(10);
{
for (int i = 0; i < purchases.size(); i++)
{
cout << "Enter a purchase amount: ";
cin >> purchases[i];
}
cout << "The purchase amounts are: " << endl;
for (int i = 0; i < 10; i++)
{
cout << purchases[i] << endl;
}
}
system("PAUSE");
return (0);
}
Upvotes: 0
Views: 54
Reputation: 206577
I can think of the following approaches.
Ask the user for the number of purchases they wish to enter. Then, create the vector
with that size.
int num;
cout << "Enter the number of purchases: ";
cint >> num;
vector<double> purchases(num);
for (int i = 0; i < num; i++)
{
cout << "Enter a purchase amount: ";
cin >> purchases[i];
}
cout << "The purchase amounts are: " << endl;
for (int i = 0; i < num; i++)
{
cout << purchases[i] << endl;
}
When asking the user for the purchase price, provide the option to enter something else to stop. After each successful read, use push_back
.
vector<double> purchases;
while ( true )
{
std::string s;
cout << "Enter a purchase amount or q to stop: ";
cin >> s;
if ( s == "q" )
{
break;
}
std::istringstream str(s);
double purchase;
str >> purchase;
purchases.push_back(purchase);
}
cout << "The purchase amounts are: " << endl;
size_t num = purchases.size();
for (int i = 0; i < num; i++)
{
cout << purchases[i] << endl;
}
Upvotes: 2