Alex
Alex

Reputation: 2289

How to issue multiple prompts to a user, depending on how many times they wish to be prompted C++

I am creating a program in C++ that allows a user to input the number of times he or she wants to be prompted for three separate inputs, ie.

how many would you like: 2
enter here: 123.45/N 32.45/W Los Angeles
enter here: 22.22/N 223.4/E Hong Kong

The way I get the three separate inputs is by creating three string variables, and doing this:

cin << input1 << input2;
getline(cin, input3);

I have a parser in a separate file that I created that gets the number input out of the first two strings and does some calculations on it.

The problem I'm having is visualizing how to set up a system only using the std library, where I can have the user enter the number of times they want to input places, and then have the program create 3 unique strings I can reference later for calculations, and have it do cin/getline the amount of times the user enters.

One way I thought of was creating a function that takes an integer (the amount the user entered) and goes through a for loop which calls cin and getline. The problem with that is, how do I save and reference the values the user inputs for calculations later on? ie.

void inputAmount(int n) {
    for(int i = 0; i < n; i++) {
        cin << input1 << input2;
        getline(cin, input3);
    }
}

Where n is the amount of lines the user wants to enter. I tried to create an array of strings and initializing it with (n * 3) elements, but that apparently doesn't work with C++ since the variable must be constant and declared. I'm just confused on how to proceed, or how to achieve this.

Upvotes: 0

Views: 1399

Answers (1)

Null
Null

Reputation: 1970

You can use a std::vector instead of an array. A std::vector does not require a size at compile time. Your code would look something like this:

string input1, input2, input3;
int n; // number of lines
vector<string> v; // vector to hold the lines

// prompt user for number of lines
cout << "how many lines?" << endl;
cin >> n;

for (int i = 0; i < n; i++) {
  cin << input1 << input2;
  getline(cin, input3);
  // parse and put back into input1, input2, etc. or some other variable as needed
  v.push_back(input1);
  v.push_back(input2);
  v.push_back(input3);
}

The call to push_back() adds the element to the vector. You can access the elements with an iterator or with the [] operator (same as an array). It would probably be better to create a struct to store the three inputs together, in which case you would parameterize the vector with your struct instead of a string, but this is the basic idea.

Upvotes: 1

Related Questions