I found this program online, and I wanted to manipulate it some, but can't figure out what to fix, I keep hitting a bump. Here is the code.
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 50 51 52 53 54 55 56 57 58
|
#include <algorithm> // std::sort
#include <cstddef> // std::size_t
#include <iostream>
#include <limits> // std::numeric_limits
#include <string>
std::size_t getNameCount()
{
std::cout << "How many names would you like to enter? ";
std::size_t length{};
std::cin >> length;
return length;
}
// Asks user to enter all the names
void getNames(std::string* names, std::size_t length)
{
// Ignore the line feed that was left by std::cin.
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
for (std::size_t i{ 0 }; i < length; ++i)
{
std::cout << "Enter name #" << i + 1 << ": ";
std::getline(std::cin, names[i]);
}
}
// Prints the sorted names
void printNames(std::string* names, std::size_t length)
{
std::cout << "\nHere is your sorted list:\n";
for (std::size_t i{ 0 }; i < length; ++i)
std::cout << "Name #" << i + 1 << ": " << names[i] << '\n';
}
int main()
{
std::size_t length{ getNameCount() };
// Allocate an array to hold the names
auto* names{ new std::string[length]{} };
getNames(names, length);
// Sort the array
std::sort(names, names + length);
printNames(names, length);
// don't forget to use array delete
delete[] names;
// we don't need to set names to nullptr/0 here because it's going to go out
// of scope immediately after this anyway.
return 0;
}
|
Can someone tell me how this program would work, if we wanted to enter more information?
So instead of just having the name, maybe name, favorite color, and random age.
So the program will ask, how many people?
so, lets say 2.
Then it would it run like so...
"Enter name of one person:"
"Enter their favorite color:"
then to the next person...
"Enter name of next person:"
"Enter their favorite color:"
then it would just print that information with a random age...
Name: Joe
Color: Blue
Weight 125lbs
Name: Mark
Color: Green
weight: 220lbs
Any idea? I've been working on something like this...thanks. I don't care about the sorting. I want to see how to use the "new" in arrays, not vectors.
thanks