简体   繁体   中英

Dynamic Space separated inputs in C++ program

I am trying to solve a problem which has likeness of the coding questions asked in programming-war sites like HackerEarth.

Let me give you a background of problem, though it seems to be unrelevant: I am trying to determine how many of muffins can be created with given units of ingredients. The code I have written so far which works with fixed inputs given, is below:

#include <iostream>

using namespace std;

int main()
{
    int N, RA, RB, RC, TA, TB, TC, TM;
    float Temp1, Temp2, Temp3;

    cout << "\nHow many various ingredients are required for creating 1 Muffin? ";
    cin >> N;

    cout << "\nHow much amount of ingredient A is needed to make 1 Muffin? ";
    cin >> RA;
    cout << "\nHow much amount of ingredient B is needed to make 1 Muffin? ";
    cin >> RB;
    cout << "\nHow much amount of ingredient C is needed to make 1 Muffin? ";
    cin >> RC;

    cout << "\nHow much amount of ingredient A is present in Kitchen? ";
    cin >> TA;
    cout << "\nHow much amount of ingredient B is present in Kitchen? ";
    cin >> TB;
    cout << "\nHow much amount of ingredient C is present in Kitchen? ";
    cin >> TC;

    Temp1 = TA / RA;
    Temp2 = TB / RB;
    Temp3 = TC / RC;

    if (Temp1 == (int) Temp1 && Temp1 > Temp2 && Temp1 > Temp3) {
        TPG = Temp1;
    } else if (Temp2 == (int) Temp2 && Temp2 > Temp1 && Temp2 > Temp3) {
        TPG = Temp2;
    } else {
        TPG = Temp3;
    }
    cout << "\nNo. of Muffins can be created: " << TPG;
    return 0;
}

Now I know that scanf can accept space-separated arguments as input, but that again would be fixed static inputs, which will fail when tested with Sample Test case given like below:

5 (Total no. of different ingredients needed to make 1 muffin)
2 4 6 8 10 (Qty. of each ingredient needed to make 1 muffin)
20 40 50 70 90 (Total Qty. of each ingredient present in the kitchen)

Now I had stopped coding in CPP, since last few years, so I can't get the idea of how do I make my program accept dynamic number of space-delimited arguments, instead of pre-fixed inputs?

Use a loop and a vector. If first number tells you number of input:

size_t n;
std::cin >> n;
std::vector<int> quantities(n);
for (auto& q : quantities) std::cin >> q;

No error checking included: That is: Assuming the user enters n valid numbers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM