In an exercise I was asked to build a program that allows collecting the most frequent destinations for a Taxi company and the most frequent stations for a Bus company.
An example of input would be:
Rappido
3
Aeropuerto Jorge Chavez
Costa Verde
Cerro San Cristobal
Rutta
2
Arequipa
Trujillo
And the output should be more or less like this:
Rappido tiene los siguientes lugares mas visitados:
1) Aeropuerto Jorge Chavez
2) Costa Verde
3) Cerro San Cristobal
Rutta tiene los siguientes lugares mas visitados:
1) Arequipa
2) Trujillo
I have the following code, however, when compiling it, it throws me the following error: Program terminated with signal SIGSEGV, Segmentation fault. So how can I iterate and save the place names in each string array and then print them? or what is wrong in my code and how can I fix it? Thank you very much in advance :D
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string nombreTaxi, nombreBus;
int cantidadTaxi=0, cantidadBus=0;
string destinos[cantidadTaxi];
string estaciones[cantidadBus];
getline(cin,nombreTaxi);
cin >> cantidadTaxi;
int i=0;
while(i<cantidadTaxi)
{
getline(cin,destinos[i]);
i++;
}
getline(cin,nombreBus);
cin >> cantidadBus;
int j=0;
while(j<cantidadBus)
{
getline(cin,estaciones[j]);
j++;
}
cout << nombreTaxi << " tiene los siguientes lugares mas visitados: " << endl;
for (int k=0; k<cantidadTaxi;k++)
{
cout << k+1 << ") " << destinos[k] << "\n";
}
cout << endl;
cout << " " << endl;
cout << nombreBus << " tiene los siguientes lugares mas visitados: " << endl;
for (int l=0; l<cantidadBus;l++)
{
cout << l+1 << ") " << estaciones[l] << "\n";
}
cout << endl;
return 0;
}
Arrays 1 in C++ must have a known size at compile time, a variable is a known value at run time and as such cannot be used as an array size:
On the other hand, the size of
destinos
y will not automagicallyestaciones
change when you read the variables, the C++ code is executed from top to bottom and what happens on subsequent lines does not affect what happened on previous lines.If you want dynamically resized collections of data, use containers.
std::map
In your case it is probablystd::vector
appropriate:You can see the code working in Try it online!.
1 Also known as arrays .