samedi 10 juin 2023

push_back() not working on more than one vector in one function...why?

I'm new to coding (and to Stack Overflow), learning about the basics of C++ right now. I want to write a simple program that: A) collects days (strings) of a week B) collects numbers (ints) that represent orders delivered during the week, and C) prints out the day - order pairs.

I've been trying to use push_back() to do this, and it seems like whatever I do, push_back() works only on the first vector. Does anyone know why this is? Am I missing something fundamental about push_back()? Any help is greatly appreciated!^-^

The result of this code right now is a runtime error coming from the last part where I try to print the pairs. When you remove the orders vector from cout, the code works... This is why I think that the problem is that somehow push_back() doesn't work on the orders vector, and therefore its non-existent elements cannot be printed. What do you think?


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

int main()
{

// collecting workdays:
// example input: Monday Tuesday Friday
cout << "Please enter the days you have worked on during this week:\n";

vector <string> days;

for (string s; cin >> s; ) 
    days.push_back(s);

// collecting orders delivered:
// example input: 11 12 10
cout << "Please enter the number of orders you delivered each day this week:\n";

vector <int> orders;

for (int x; cin >> x; )
    orders.push_back(x);

// printing day - order pairs
/* desired output based on the example input & output:
Monday = 11 orders
Tuesday = 12 orders
Friday = 10 orders */
for (int i = 0; i < days.size(); ++i)
    cout << days[i] << " = " << orders[i] << "orders\n";

return 0;
}

Aucun commentaire:

Enregistrer un commentaire