I use pointers to print the contents of a string array for this program, I have trouble in printing out the item's names. Whatever I enter how many items, it prints out only one item. For example, when I entered pencil, pen, book, it only printed out the last item 3 times: book book book instead of printing: pencil pen book.
void getPrint(string *names, int num){
cout <<"Here is the items you entered: ";
for (int i=0; i<num; i++){
cout <<*names<<" ";
}
Maybe you want to treat the pointer to a single string as an array:
void getPrint(string * names, int num)
{
for (int i = 0; i < num; ++i)
{
cout << names[i] << " ";
}
cout << endl;
}
There are other possibilities:
cout << names++ << " ";
cout << *(names + i) << " ";
Look up pointer dereferencing in your favorite reference.
The preferred solution is to use std::vector<string> or std::array<string>.
void getPrint(const std::vector<std::string>& names)
{
const unsigned int quantity = names.size();
for (unsigned int i = 0; i < quantity; ++i)
{
std::cout << names[i] << " ";
}
std::cout << endl;
}
There are two possibilies:
Array syntax
Your treat your std::string as an array and increment over its indices. To be consistent you can pass the argument in array syntax as well.
void getPrint(const std::string names[], const int num){
std::cout <<"Here is the items you entered: " << std::endl;
for (int i=0; i<num; i++){
std::cout <<names[i]<<" " << std::endl;
}
}
Pointer syntax
You pass your std::string as a pointer (on the first element of you array). To reach all your elements you have to increment the pointer itself.
void getPrint(const std::string* names, const int num){
std::cout <<"Here is the items you entered: " << std::endl;
for (int i=0; i<num; i++){
std::cout <<*(names++)<<" " << std::endl; // increment pointer
}
}
Since incrementing your pointer does not need the index i anymore you can shorten the whole thing a bit (but may not declare const num anymore).
void getPrint(const std::string* names, int num){
std::cout <<"Here is the items you entered: " << std::endl;
while(num--){
std::cout <<*(names++)<<" " << std::endl;
}
}
Hope I could help you.
Edit
As mentioned above any solution using the STL containers std::vector or std::array and passing them by reference are preferred. Since they provide .begin() and .end() methods one can use (C++11)
void getPrint(const std::vector<std::string>& names){
std::cout <<"Here is the items you entered: " << std::endl;
for (auto name: names){
std::cout << name << " " << std::endl;
}
}
Related
So, I have a vector of boats. I need to access these boats and modify them (i.e. delete them) regularly, so it would be really nice if I could print their index along with all their other information, but I can't seem to figure out how.
The closest I got to it was with a simple for loop, but that eventually prints the current index along with the previous ones, as the vector size grows (since my i was < vector.size())
vector <Boat> berths_reg;
//print vector elements info
void Boat::print_info()
{
cout << endl;
for(int i = 0; i < berths_reg.size(); i++)
{
cout << "Index : " << i << endl;
}
cout << "Boat type : " << type << endl;
cout << "Boat length : " << length << endl;
cout << "Draft depth : " << draft << endl;
cout << endl;
}
//iterate through vector to print all elements
void print_vector()
{
vector <Boat> ::iterator it;
for (it = berths_reg.begin(); it != berths_reg.end(); ++it)
{
it->print_info();
}
}
//Storing boats (objects data) inside vector
void add_boat(Boat* b, string type, int length, int draft)
{
b->get_type(type);
b->get_length(length);
b->get_draft(draft);
berths_reg.push_back(*b);
}
Simply print both the index and the info within the same loop:
void print_vector()
{
for(int i = 0; i < berths_reg.size(); ++i)
{
cout << "Index : " << i << endl;
berths_reg[i].print_info();
}
}
I'm trying to use displayVectorVer2() to have it only display the first 10 elements, but I don't know how to do it with iterators. I did try a few dumb things just to see what would happen: I compared the iterator to displayLimit in my for loop. I played around by subtracting vobj.end()-5 since my professor is only having me use 15 elements, but I fully well knew this was not a good idea.
#include <iostream>
#include <vector>
#include <ctime>
template <class T>
void fillVector(std::vector<T>& vobj, int n);
template <class T>
void displayVectorVer2(std::vector<T>& vobj, typename std::vector<T>::iterator ptr);
template <class T>
void fillVector(std::vector<T>& vobj, int n)
{
srand((unsigned int)time(NULL));
for (int i=0; i<n; ++i)
{
vobj.push_back(rand()%99999+1);
}
}
template <class T>
void displayVectorVer2(std::vector<T>& vobj, typename std::vector<T>::iterator ptr)
{
std::cout << "Vector object contains " << vobj.size() << " values which are" << std::endl;
const unsigned displayLimit = 10;
if (vobj.size()>displayLimit)
{
for (ptr=vobj.begin(); ptr<vobj.end(); ++ptr)
{
std::cout << " " << *ptr;
}
std::cout << " ..." << std::endl;
}
else
{
for (ptr=vobj.begin(); ptr<vobj.end(); ++ptr)
{
std::cout << " " << *ptr;
}
std::cout << std::endl;
}
}
int main()
{
std::vector<int> vobj;
std::cout << "Before calling fillVector(...): vobj contains "
<< vobj.size() << " values." << std::endl;
std::cout << "\nEnter # of random values you'd like to store in vobj: ";
int n;
std::cin >> n;
std::cout << "\n*** Calling fillVector(...) ***" << std::endl;
fillVector(vobj, n);
std::cout << "\n*** Calling displayVectorVer2(...) ***" << std::endl;
std::vector<int>::iterator ptr;
displayVectorVer2(vobj,ptr);
}
Maybe I am thinking too simple but, that wold solve your question:
I'm trying to use displayVectorVer2() to have it only display the
first 10 elements
without knowing your full exercise, that would be my answer:
...
const unsigned displayLimit = 10;
if (vobj.size()>displayLimit)
{
for (ptr=vobj.begin(); ptr<vobj.begin()+displayLimit; ++ptr)
{
std::cout << " " << *ptr;
}
std::cout << " ..." << std::endl;
}
else
...
edit:
That worked, but why does it work? I remember adding to vobj.begin() and getting extra empty elements appended to the original vector.
Not sure what exactly you did but maybe that helps you understanding your code:
...
const unsigned displayLimit = 10;
if (vobj.size()>displayLimit)
{
//Init ptr outside the for loop
ptr = vobj.begin();
//What the for loop is seeing with a more familiar syntax:
//for( ; i < 0 +displayLimit; ++i)
//what you are seeing
for (/*ptr init*/; ptr < vobj.begin() +displayLimit; ++ptr)
{
std::cout << " " << *ptr;
}
std::cout << " ..." << std::endl;
}
...
The iterators just gives you the int value and you can use it with what ever "eats" int values. In your case the for loop.
If you tell the program to use an iterator you tell the program: "Just give me the number the Vector begins with and add 10".
In your case 0 "...and add 10"
You could also write a code like that with n passed to the function
for being able to use .end - input + 10 for showing 10 lines:
...
template <class T>
void displayVectorVer2(std::vector<T>& vobj, typename std::vector<T>::iterator ptr,int n)
{
std::cout << "Vector object contains " << vobj.size() << " values which are" << std::endl;
const unsigned displayLimit = 10;
if (vobj.size()>displayLimit)
{
ptr=vobj.begin();
for (; ptr<vobj.end() -n +displayLimit; ++ptr)
{
std::cout << " " << *ptr;
}
std::cout << " ..." << std::endl;
}
else
{
for (ptr=vobj.begin(); ptr<vobj.end(); ++ptr)
{
std::cout << " " << *ptr;
}
std::cout << std::endl;
}
}
int main()
{
std::vector<int> vobj;
std::cout << "Before calling fillVector(...): vobj contains "
<< vobj.size() << " values." << std::endl;
std::cout << "\nEnter # of random values you'd like to store in vobj: ";
int n;
std::cin >> n;
std::cout << "\n*** Calling fillVector(...) ***" << std::endl;
fillVector(vobj, n);
std::cout << "\n*** Calling displayVectorVer2(...) ***" << std::endl;
std::vector<int>::iterator ptr;
displayVectorVer2(vobj,ptr,n);
}
...
You also shouldn't use srand in modern code anymore since it is depricated for more than 10 years since c++11 introduced <random>
and srand can harm your program f.e. if used for generating seeds for sensitive code. Also srand provides not the "randomness" it should provide, srand generates some numbers more often than others - that's not random.
I want to increase the size of the array of string after declaring it once, how can it be done. I need to increase the size in the following code..
#include<iostream>
using namespace std;
#include<string>
int main()
{
int n;
string A[] =
{ "vaibhav", "vinayak", "alok", "aman" };
int a = sizeof(A) / sizeof(A[0]);
cout << "The size is " << a << endl;
for (int i = 0; i < a; i++)
{
cout << A[i] << endl;
}
cout << "Enter the number of elements you want to add to the string"
<< endl;
cin >> n;
cout << "ok now enter the strings" << endl;
for (int i = a; i < n + a; i++)
{
cin >> A[i];
}
a = a + n;
A.resize(a); // THIS KIND OF THING
for (int i = 0; i < a; i++)
{
cout << A[i] << endl;
}
return 0;
}
Plain and simple: you cannot.
You can get a larger array, copy all your stuff over and use that instead. But why do all that, when there is a perfectly good class already there, doing it all for you: std::vector.
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> A = {"vaibhav", "vinayak", "alok", "aman"};
std::cout << "The size is " << A.size() << std::endl;
for(string s : A)
{
std::cout << s << std::endl;
}
// want to enter more?
sd::string more;
std::cin >> more;
A.push_back(more);
std::cout << "The size is " << A.size() << std::endl;
for(string s : A)
{
std::cout << s << std::endl;
}
return 0;
}
Convert your code over to use std::vector and this problem becomes much easier to solve.
#include<iostream>
#include<string>
#include<vector>
int main(){
int n;
std::vector<std::string> A = {"vaibhav", "vinayak", "alok", "aman"};
int a = A.size();
std::cout << "The size is " << a << std::endl;
//Prefer Range-For when just iterating over all elements
for(std::string const& str : A){
std::cout << str << std::endl;
}
std::cout << "Enter the number of elements you want to add to the string" << std::endl;
std::cin >> n;
std::cout << "ok now enter the strings" << std::endl;
for(int i = 0; i < n; i++ ) {
//emplace_back automatically resizes the container when called.
A.emplace_back();
std::cin >> A.back();
//If you're using C++17, you can replace those two lines with just this:
//std::cin >> A.emplace_back();
}
for(std::string const& str : A){
std::cout << str << std::endl;
}
return 0;
}
Also, don't use using namespace std;, since it leads to expensive to fix bugs and makes your code harder to read for other C++ programmers.
I want to increase the size of the array of string after declaring it
once, how can it be done.
It cannot be done. Use std::vector if the element count isn't known at compile time or can change dynamically. It even has a resize member function named exactly like the one in your code.
You cannot increase the size of a Raw Array, you could use an std::vecto<std::string> as this type of array can grow at runtime.
However, you could also create a class that will store an array of string and create your own implementation to resize the raw array. Which would be creating a bigger array and copying all the other values over, then setting the class array to the new array (or just return it)
Goal state: I'm supposed to display a result where by randomized e.g. Set S = {dog, cow, chicken...} where randomized size can be 1-12 and animals cannot be replicated so once there is cow, there cannot be another cow in Set S anymore.
Error: I've been displaying a correct randomized size of 1-12. However I have duplicated animals even though I tried to check whether the animal exist in set S before I insert it into Set S.
UPDATE: I couldnt get it to run after the various updates by stackoverflow peers.
Constraints: I have to use pointers to compare with pointers - dynamically.
"Important Note
All storages used for the arrays should be dynamically created; and delete them when
they are no longer needed.
When accessing an element of the array, you should access it via a pointer, i.e. by
dereferencing this pointer. Using the notation, for example set [k] or *(set + k)
accessing to the kth element of the set is not allowed."
Do hope to hear your advice, pals!
Best regards,
MM
/*
MarcusMoo_A2.cpp by Marcus Moo
Full Time Student
I did not pass my assignment to anyone in the class or copy anyone’s work;
and I'm willing to accept whatever penalty given to you and
also to all the related parties involved
*/
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <ctime>
using namespace std;
/* Global Declaration */
const int MAX = 12; // 12 animals
const int MAXSTR = 10;
typedef char * Element;
static Element UniversalSet [MAX] = {"Rat", "Ox", "Tiger", "Rabbit", "Dragon",
"Snake", "Horse", "Sheep", "Monkey", "Rooster", "Dog", "Pig"};
/* Functions */
// Construct a set
void option0(int); // Menu Option 0
void constructSet (Element *, int); // Construct a set
bool checkElement (Element *, Element *, int); // Check element for replicates
int main()
{
// Declarations
int mainSelect;
int size=rand()%12+1; // Random construct
srand (time(NULL)); // Even better randomization
cout << "Welcome to MARCUS MOO Learning Center" << endl;
do
{
cout << "0. An example of set" << endl;
cout << "1. Union" << endl;
cout << "2. Intersection" << endl;
cout << "3. Complement" << endl;
cout << "4. Subset of" << endl;
cout << "5. Equality" << endl;
cout << "6. Difference " << endl;
cout << "7. Distributive Law" << endl;
cout << "9. Quit" << endl;
cout << endl;
if (mainSelect==0)
{
option0(size);
}
cout << "Your option: ";
cin >> mainSelect;
cout << endl;
} while(mainSelect!=9);
return 0;
}
/* Functions */
// Option 0 - An example of set
void option0 (int size)
{
// Mini Declaration
int again;
Element *S;
do
{
cout << "Here is an example on set of animals" << endl;
cout << endl;
// Build set S
constructSet (S,size);
// Display set S
Element *S = &S[0];
cout << "Set S = {";
for (int i = 0; i < size; i++)
{
if (i!=size)
{
cout << *S
<< ", ";
}
else
{
cout << *S
<< "}"
<< endl;
}
S++;
}
cout << endl;
cout << "Note that elements in S are distinct are not in order" << endl;
cout << endl;
// Option 0 2nd Part
cout << "Wish to try the following operations?" << endl;
cout << "1. Add an element to the set" << endl;
cout << "2. Check the element in the set" << endl;
cout << "3. Check the cardinality" << endl;
cout << "9. Quit" << endl;
cout << endl;
cout << "Your choice: ";
cin >> again;
} while (again!=9);
}
// Construct a set
void constructSet (Element *set, int size)
{
// Declarations
Element *ptrWalk;
ptrWalk = &set[0];
int randomA=0;
for (int i = 0;i<size;i++)
{
bool found = true;
while (found)
{
randomA = rand()%MAX; // avoid magic numbers in code...
*ptrWalk = UniversalSet [randomA];
// Ensure no replicated animals in set S
found = checkElement (ptrWalk, set, i);
}
set=ptrWalk;
set++;
}
}
bool checkElement (Element *ptrWalk, Element *set, int size)
{
for (int j=0; j<size;j++)
{
if (ptrWalk==&set[j])
{
return true;
}
}
return false;
}
You have 2 different major problems in your code. First has already be given by Federico: checkElement should return true as soon as one element was found. Code should become simply (but please notice the < in j<size):
bool checkElement (char *ptrWalk, int size)
{
for (int j=0; j<size;j++)
{
if (ptrWalk==S[j])
{
return true;
}
}
return false;
}
The second problem is that you should not search the whole array but only the part that has already been populated. That means that in constructSet you should call checkElement(ptrWalk, i) because the index of current element is the number of already populate items. So you have to replace twice the line
found = checkElement (*ptrWalk, size);
with this one
found = checkElement (*ptrWalk, i);
That should be enough for your program to give expected results. But if you want it to be nice, there are still some improvements:
you correctly declared int main() but forgot a return 0; at the end of main
you failed to forward declare the functions while you call them before their definition (should at least cause a warning...)
you make a heavy use of global variables which is not a good practice because it does not allow easy testing
your algorithms should be simplified to follow the Dont Repeat Yourself principle. Code duplication is bad for future maintenance because if forces to apply code changes in different places and omission to do so leads to nasty bugs (looks like this is bad but I've already fixed it - yes but only in one place...)
constructSet could simply be:
// Construct a set
void constructSet (Element *set, int size)
{
// Declarations
//Element *ptrBase;
voidPtr *ptrWalk;
ptrWalk = &set[0];
int randomA=0;
for (int i = 0;i<size;i++)
{
bool found = true;
while (found) {
randomA = rand()%MAX; // avoid magic numbers in code...
*ptrWalk = UniversalSet [randomA];
// Ensure no replicated animals in set S
found = checkElement (*ptrWalk, i);
}
ptrWalk++;
}
}
Main problem is that 'break' is missing in checkElement() once it finds the element. If you do not break the loop, it will compare with other indices and overwrite the 'found' flag.
if (ptrWalk==S[j])
{
found = true;
break;
}
Also, use ptrWalk as temporary variable to hold the string. Add the string to S only after you make sure that it is not present already.
void constructSet (Element *set, int size)
{
// Declarations
//Element *ptrBase;
Element ptrWalk;
//ptrWalk = &set[0];
int randomA=0;
int randomB=0;
bool found = false;
for (int i = 0;i<size;i++)
{
randomA = rand()%12;
ptrWalk = UniversalSet [randomA];
// Ensure no replicated animals in set S
found = checkElement (ptrWalk, i);
if (found==true)
{
do
{
// Define value for S
randomB = rand()%12;
ptrWalk = UniversalSet [randomB];
found = checkElement (ptrWalk, i);
} while(found==true);
S[i] = UniversalSet [randomB];
//ptrWalk++;
}
else
{
// Define value for S
S[i] = UniversalSet [randomA];
//ptrWalk++;
}
}
}
You need to optimize your code by removing unnecessary variables and making it less complex.
I have fixed this with the guidance of my C++ lecturer! You guys may take a reference from this to solve your pointers to pointers dilemma next time! Cheers!
/*
MarcusMoo_A2.cpp by Marcus Moo
Full Time Student
I did not pass my assignment to anyone in the class or copy anyone’s work;
and I'm willing to accept whatever penalty given to you and
also to all the related parties involved
*/
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <ctime>
using namespace std;
/* Global Declaration */
const int MAX = 12; // 12 animals
const int MAXSTR = 10;
typedef char * Element;
static Element UniversalSet [MAX] = {"Rat", "Ox", "Tiger", "Rabbit", "Dragon",
"Snake", "Horse", "Sheep", "Monkey", "Rooster", "Dog", "Pig"};
/* Functions */
// Construct a set
void option0(int); // Menu Option 0
void constructSet (Element *, int); // Construct a set
bool checkElement (Element, Element *, int); // Check element for replicates
// This function is to get a random element
// with storage allocated
Element getAnElement ()
{
Element *p = &UniversalSet [0];
int k = rand () % MAX;
for (int i = 0; i < k; i++)
++p;
Element e = new char [MAXSTR];
strcpy (e, *p);
return e;
}
int main()
{
// Declarations
int mainSelect;
int size=rand()%12; // Random construct
srand (time(NULL)); // Even better randomization
cout << "Welcome to MARCUS MOO Learning Center" << endl;
do
{
cout << "0. An example of set" << endl;
cout << "1. Union" << endl;
cout << "2. Intersection" << endl;
cout << "3. Complement" << endl;
cout << "4. Subset of" << endl;
cout << "5. Equality" << endl;
cout << "6. Difference " << endl;
cout << "7. Distributive Law" << endl;
cout << "9. Quit" << endl;
cout << endl;
if (mainSelect==0)
{
option0(size);
}
cout << "Your option: ";
cin >> mainSelect;
cout << endl;
} while(mainSelect!=9);
return 0;
}
/* Functions */
// Option 0 - An example of set
void option0 (int size)
{
// Mini Declaration
int again;
Element *S;
// You need to assign storage
S = new Element [MAX];
for (int i = 0; i < MAX; i++)
S [i] = new char [MAXSTR];
do
{
cout << "Here is an example on set of animals" << endl;
cout << endl;
// Build set S
constructSet (S,size);
// Display set S
Element *p = &S[0]; // Change to p
cout << "Set S = {";
for (int i = 0; i < size; i++)
{
if (i!=size-1)
{
cout << *p
<< ", ";
}
else
{
cout << *p
<< "}"
<< endl;
}
p++;
}
cout << endl;
cout << "Note that elements in S are distinct are not in order" << endl;
cout << endl;
// Option 0 2nd Part
cout << "Wish to try the following operations?" << endl;
cout << "1. Add an element to the set" << endl;
cout << "2. Check the element in the set" << endl;
cout << "3. Check the cardinality" << endl;
cout << "9. Quit" << endl;
cout << endl;
cout << "Your choice: ";
cin >> again;
} while (again!=9);
}
// Construct a set
void constructSet (Element *set, int size)
{
// Declarations
Element *ptrWalk;
ptrWalk = &set[0];
int randomA=0;
Element temp = new char [MAXSTR];
for (int i = 0;i<size;i++)
{
bool found = true;
while (found)
{
// randomA = rand()%MAX; ..
temp = getAnElement ();
// Ensure no replicated animals in set S
found = checkElement (temp, set, i);
}
// set=ptrWalk;
// set++;
strcpy (*ptrWalk, temp);
++ptrWalk;
}
}
bool checkElement (Element ptrWalk, Element *set, int size)
{
Element *p = &set[0];
for (int j=0; j<size;j++)
{
if (strcmp (ptrWalk, *p) == 0)
{
return true;
}
p++;
}
return false;
}
I'm trying to read names and ages from user, until user inputs "stop". Then just print all these values. Please help me , I'm just the beginner in C++
// Pass.cpp
// Reading names and ages from user and outputting them
#include <iostream>
#include <iomanip>
#include <cstring>
using std::cout;
using std::cin;
using std::endl;
using std::setw;
using std::strcmp;
char** larger(char** arr);
int* larger(int* arr);
void read_data(char*** names, int** ages);
void print_data(char*** names, int** ages);
int main()
{
char** names = new char*[5];
char*** p_names = &names;
int* ages = new int[5];
int** p_ages = &ages;
read_data(p_names,p_ages);
print_data(p_names,p_ages);
}
void read_data(char*** names, int** ages)
{
const char* sent = "stop";
const int MAX = 15;
int count = 0;
char UI[MAX];
cout << "Enter names and ages."
<< endl << "Maximum length of name is " << MAX
<< endl << "When stop enter \"" << sent << "\".";
while (true)
{
cout << endl << "Name: ";
cin.getline(UI,MAX,'\n');
if (!strcmp(UI, sent))
break;
if (count + 1 > sizeof (&ages) / sizeof (&ages[0]))
{
*names = larger(*names);
*ages = larger(*ages);
}
*names[count] = UI;
cout << endl << "Age: ";
cin >> *ages[count++];
}
}
void print_data(char*** names, int** ages)
{
for (int i = 0; i < sizeof(*ages) / sizeof(*ages[0]);i++)
{
cout << endl << setw(10) << "Name: " << *names[i]
<< setw(10) << "Age: " << *ages[i];
}
}
char** larger(char** names)
{
const int size = sizeof(names) / sizeof(*names);
char** new_arr = new char*[2*size];
for (int i = 0; i < size; i++)
new_arr[i] = names[i];
return new_arr;
}
int* larger(int* ages)
{
const int size = sizeof(ages) / sizeof(*ages);
int* new_arr = new int[2 * size];
for (int i = 0; i < size; i++)
new_arr[i] = ages[i];
return new_arr;
}
You are really over complicating things.
Given the original problem:
Write a program that reads a number (an integer) and a name (less than
15 characters) from the keyboard. Design the program so that the data
is done in one function, and the output in another. Store the data in
the main() function. The program should end when zero is entered for
the number. Think about how you are going to pass the data between
functions
The problem wants you to think about passing parameters to functions. A simple solution would be:
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
// Pass in a char array and an integer reference.
// These values will be modified in the function
void read_data(char name[], int& age)
{
cout << endl << "Age: ";
cin >> age;
cin.ignore();
cout << endl << "Name: ";
cin.getline(name, 16);
}
// Pass a const array and an int value
// These values will not be modified
void print_data(char const *name, int age)
{
cout << endl << setw(10) << "Name: " << name
<< setw(10) << "Age: " << age;
}
int main()
{
char name[16];
int age;
cout << "Enter names and ages."
<< endl << "Enter 0 age to quit.";
do {
read_data(name, age);
print_data(name, age);
} while (0 != age)
}
EDIT: Modified per user3290289's comment
EDIT2: Storing data in an array
// Simplify by storing data in a struct (so we don't have to manage 2 arrays)
struct Person {
char name[16];
int age;
};
// Returns how many People were input
int read_data(Person*& arr)
{
int block = 10; // How many persons to allocate at a time
arr = NULL;
int arr_size = 0;
int index = 0;
while (true) {
if (index == arr_size) {
arr_size += block;
arr = (Person *)realloc(arr, arr_size * sizeof(Person)); // Reallocation
// Should check for error here!
}
cout << endl << "Age: ";
cin >> arr[index].age;
cin.ignore();
if (0 == arr[index].age) {
return index;
}
cout << endl << "Name: ";
cin.getline(arr[index++].name, 16);
}
}
void print_data(Person *arr, int count)
{
for (int i = 0; i < count; i++) {
cout << endl << setw(10) << "Name: " << arr[i].name
<< setw(10) << "Age: " << arr[i].age;
}
}
int main()
{
Person *arr;
int count = read_data(arr);
print_data(arr, count);
free(arr); // Free the memory
}
try this:
#include <iostream>
#include <iomanip>
#include <vector>
#include <sstream>
using std::cout;
using std::cin;
using std::endl;
using std::setw;
using std::strcmp;
void read_data(std::vector<std::string> &names, std::vector<int> &ages);
void print_data(std::vector<std::string> &names, std::vector<int> &ages);
int main()
{
std::vector<std::string> names;
std::vector<int> ages;
read_data(names, ages);
print_data(names, ages);
}
void read_data(std::vector<std::string> &names, std::vector<int> &ages)
{
const char* sent = "stop";
cout << "Enter names and ages."
<< endl << "When stop enter \"" << sent << "\".";
while (true)
{
std::string input;
cout << endl << "Name: ";
std::getline(cin, input);
if (!strcmp(input.c_str(), sent))
break;
names.push_back(input);
cout << endl << "Age: ";
std::string age;
std::getline(cin, age);
ages.push_back(atoi(age.c_str()));
}
}
void print_data(std::vector<std::string> &names, std::vector<int> &ages)
{
for (int i = 0; i < names.capacity() ; i++)
{
cout << endl << setw(10) << "Name: " << names.at(i)
<< setw(10) << "Age: " << ages.at(i);
}
}
One problem I see is this if statement:
if (count + 1 > sizeof (&ages) / sizeof (&ages[0]))
&ages is the address of an int**, a pointer, and so it's size is 8 (usually) as that is the size of a pointer type. The function does not know the size of the array, sizeof will only return the correct answer when ages is declared in the same scope.
sizeof(&ages) / sizeof(&ages[0])
will always return 1
I believe one natural solution about this problem is as follows:
create a "std::map" instance. Here std::map would sort the elements according to the age. Here my assumption is after storing the data into the container, you would like to find about a particular student age/smallest/largest and all various manipulation with data.Just storing and printing the data does not make much sense in general.
create a "std::pair" and take the both input from the user into the std::pair "first" and "second" member respectively. Now you can insert this "std::pair" instance value into the above "std::map" object.
While printing, you can now fetch the each element of "std::map" in the form of "std::pair" and then you can display pair "first" and "second" part respectively.