goto is bad, very bad. You have no way to programmatically terminate your
goto loop. You can use a
while or
do/while loop.
What happens if your car model is two words (or more)? Getting input from the keyboard from
std::cin will stop at the first space so your next attempt to input data from the keyboard can fail because there is still data in the input buffer. Use
std::getline (from the
<string> header) to get the entire input line including spaces.
std::cin leaves the carriage return in the buffer,
std::getline removes it, so you could get erroneous input. Ignore what's in the buffer with
std::cin::ignore.
You were trying to pass a
std::string array into functions that have a
std::string (NOT array) as the first parameter.
No need for global variables, you create in
main and pass into your functions. Passed as references (&), not by value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
#include <iostream>
#include <string>
void enter(std::string cars[], int&);
void show(std::string cars[], const int&);
int main()
{
int decision { };
int i { };
std::string cars[100];
do
{
std::cout << "1 to enter a new car model, 2 for car list (-1 to exit): ";
std::cin >> decision;
std::cin.ignore(100, '\n');
if (decision == 1)
{
enter(cars, i);
}
if (decision == 2)
{
show(cars, i);
}
}
while (decision != -1);
}
void enter(std::string cars[], int& i)
{
std::cout << "Enter the new car model #: ";
std::getline(std::cin, cars[i]);
std::cout << '\n';
i++;
}
void show(std::string cars[], const int& i)
{
std::cout << "\nList of cars:\n";
for (int y { }; y < i; y++)
{
std::cout << cars[y] << '\n';
}
std::cout << '\n';
}
|
1 to enter a new car model, 2 for car list (-1 to exit): 1
Enter the new car model #: Volta Prime
1 to enter a new car model, 2 for car list (-1 to exit): 1
Enter the new car model #: Leaf
1 to enter a new car model, 2 for car list (-1 to exit): 1
Enter the new car model #: Tesla Big Price Tag
1 to enter a new car model, 2 for car list (-1 to exit): 2
List of cars:
Volta Prime
Leaf
Tesla Big Price Tag
1 to enter a new car model, 2 for car list (-1 to exit): -1 |