Home > Software design >  Loop isn't printing expected results
Loop isn't printing expected results

Time:10-19

I'm trying to prompt the user for items and the quantity of those items respectively. But when I run the program, it correctly displays the elements in the first vector, and not the elements in the second vector.

#include <iostream>
#include <vector>
using namespace std;

int main(){
    // Declaring vectors
    vector <string> items{};
    vector <int> quantity{};
    
    cout << "Enter name of items." << endl;
    
    // Read input to vectors
    for(int i{1}; i <= 3;   i){
        string item{};
        cin >> item;
        items.push_back(item);
    }
    cout << "Enter quantity of each item." << endl;
    
    for(int i{1}; i <= 3;   i){
        int num{};
        cin >> num;
        quantity.push_back(num);
    }
    
    // Display data
    for(auto item: items){
        int i{0};
   
        cout << "Item: " << item << " - " << "Quantity: " << quantity.at(i) << endl;
          i;

        cout << "--------------------" << endl;
    }
    return 0;
}

output

Enter name of items.
meat fish milk
Enter quantity of each item.
10 20 30
Item: meat - Quantity: 10
--------------------
Item: fish - Quantity: 10
--------------------
Item: milk - Quantity: 10
--------------------

I tried printing out quantity.at(1) and it correctly displays 20, I apologize in advance if I missed out on something obvious. I'm very new to the language.

CodePudding user response:

You can fix it by bringing the "i" variable out of the last iteration

CodePudding user response:

You are always setting i equal to the 0th element. instead move the creation of i to be outside the loop:

 int i{0};
 for(auto item: items){   
        cout << "Item: " << item << " - " << "Quantity: " << quantity.at(i) << endl;
          i;

        cout << "--------------------" << endl;
    }
  • Related