0

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);

}

3
  • 1
    You are probably looking for the resize() method. Commented Nov 17, 2016 at 1:49
  • or push_back. Commented Nov 17, 2016 at 1:56
  • or emplace_back, or insert Commented Nov 17, 2016 at 2:07

1 Answer 1

2

I can think of the following approaches.

  1. 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;
    }
    
  2. 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;
    }
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.