How to fill structs within a class from a file? - c++

I have an assignment where we need to create a class object that has many different variables, one of which being a struct. I can't figure out how to fill the struct from my setter function. I've attached some codes snippets I've pulled out of my code. my count_file_line function returns an int value of however many lines are in a txt file. I'm also really new to coding and have been struggling so if it's an obvious answer, sorry
When I run the program and try to cout teachers[I].password from within the setter function, nothing shows up (the "Flag" does show up)
struct teacher{
int id;
string password;
string first_name;
string last_name;
};
void University::set_teachers(ifstream& inFile){
int amountOfTeachers = count_file_lines(inFile);
this->teachers = new teacher[amountOfTeachers];
for(int i = 0; i < amountOfTeachers; i++){
inFile >> teachers[i].password;
inFile >> teachers[i].first_name;
inFile >> teachers[i].last_name;
cout << "Flag" << endl;
}
}

What you're trying to accomplish is a "de-serialization" of a sequence of teacher objects.
You may be interested in:
Is it possible to serialize and deserialize a class in C++?
for some general-purpose solutions. Note those may (or may not) be a bit "heavy-weight" for what you need to achieve.

Example of using tell, don't ask:
#include <iostream>
using std::cout, std::cerr, std::endl;
#include <iomanip>
using std::setw, std::setfill;
#include <fstream>
using std::ifstream, std::istream; // std::ofstream;
#include <sstream>
using std::stringstream;
#include <string>
using std::string, std::to_string;
#include <cstdint>
#include <cassert>
// stub - this function implemented and tested elsewhere
int count_file_lines(ifstream& inFile)
{
if (!inFile.good())
cerr << "\n !infile.good()" << endl;
return 5; // for test purposes
}
struct teacher
{
private:
int id; // unique number in record order
string password;
string first_name;
string last_name;
static int ID; // init value below
// note: On my system each string is 32 bytes in this object,
// regardless of char count: the chars are in dynamic memory
public:
teacher() : id(++ID) // password, first_name, last_name
{ } // default init is empty string
~teacher() = default; // do nothing
void read(istream& inFile) // tell instance to read next record
{
inFile >> password;
inFile >> first_name;
inFile >> last_name;
}
void show()
{
cout << "\n show id:" << id
<< "\n pw :" << password
<< "\n fn :" << first_name
<< "\n ln :" << last_name
<< endl;
}
};
int teacher::ID = 0; // compute unique ID number for each record
And a demo of input and output (teacher::read(), teacher::show())
Note use of "stringstream ss;". It is filled using a for loop, and passed to each teacher object using "teacher.read()".
Then the teacher values are echo'd to output using "teacher.show()"
class F834_t
{
teacher* teachers = nullptr; // do not yet know how many
ifstream inFile; // declared, but not opened
uint amountOfTeachers = 0;
stringstream ss; // for debug / demo use
public:
// use default ctor, dtor
F834_t() = default;
~F834_t() = default;
int exec(int , char** )
{
// open infile to count lines
amountOfTeachers = static_cast<uint>(count_file_lines(inFile)); // use working func
cout << "\n teacher count: " << amountOfTeachers << "\n "; // echo
// init ss with 5 values
for (uint i=1; i<=amountOfTeachers; ++i)
ss << " pw" << i << " fn" << i << " ln" << i << " ";
cout << ss.str() << endl;
teachers = new teacher[amountOfTeachers]; // allocate space, invoke default ctor of each
assert(teachers);
cout << "\n teachers: " << setw(4) << sizeof(teachers) << " (pointer bytes)"
<< "\n a teacher: " << setw(4) << sizeof(teacher) << " (teacher bytes)"
<< "\n size of all: " << setw(4) << (amountOfTeachers * sizeof(teacher))
<< " ( " << setw(3) << sizeof(teacher) << " * " << setw(3) << amountOfTeachers << ')'
<< endl;
// reset stream to start of inFIle, maybe close/open inFile
for (uint i=0;i<amountOfTeachers; ++i)
{
assert(ss.good()); // (inFile.good());
teachers[i].read(ss); // (inFile); // tell the object to read the file
}
for (uint i=0;i<amountOfTeachers; ++i)
{
teachers[i].show(); // tell the object to show its contents
}
return 0;
}
}; // class F834_t
int main(int argc, char* argv[])
{
F834_t f834;
return f834.exec(argc, argv);
}
Output - note that a much simplified input stream is created on the fly, and is echo'd early in this output.
teacher count: 5
pw1 fn1 ln1 pw2 fn2 ln2 pw3 fn3 ln3 pw4 fn4 ln4 pw5 fn5 ln5
teachers: 8 (pointer bytes)
a teacher: 104 (teacher bytes)
size of all: 520 ( 104 * 5)
show id:1
pw :pw1
fn :fn1
ln :ln1
show id:2
pw :pw2
fn :fn2
ln :ln2
show id:3
pw :pw3
fn :fn3
ln :ln3
show id:4
pw :pw4
fn :fn4
ln :ln4
show id:5
pw :pw5
fn :fn5
ln :ln5

Related

Reading a excel file in to struct c++

I want to read a excel file in to a structure.But the thing is it reads the excel columns as whole line.I need those data in columns one by one.Using fstreams I have a file opened that contains numerous columns
I tried it with the knowledge that I have.But It displays all the details as a whole column as i've shown below
Name : Name,Nick
Nick : name,Phone
Phone : number,Carrier,Address
Carrier : Yashodhara,Yash,711256677,Mobitel,"No.
Address : 29,Bollatha,Ganemulla"
-----------------------
Name : Madushani,Madu,711345678,Mobitel,"No.
Nick : 12,
Phone : Gampaha"
Carrier : Sadeepa,Sad,789002264,Hutch,"No.
Address : 123,
-----------------------
I tried this with the following code.
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
//structure for store contact details
struct contacts {
string name;
string nickName;
string phoneNumber;
string carrier;
string address;
};
int main() {
const int LIMIT = 10;
contacts limit[LIMIT];
ifstream file;
file.open("Contact.csv");
if (file) {
while (!(file.eof())) {
for (int i = 0; i <= 7; i++) {
file >> limit[i].name;
file >> limit[i].nickName;
file >> limit[i].phoneNumber;
file >> limit[i].carrier;
file >> limit[i].address;
}
}
}
else {
cout << "Error";
}
// Using the following to debug output
for (int i = 0; i < 7; i++) {
cout << "Name : " << limit[i].name << endl
<< "Nick : " << limit[i].nickName << endl
<< "Phone : " << limit[i].phoneNumber << endl
<< "Carrier : " << limit[i].carrier << endl
<< "Address : " << limit[i].address << endl
<< "-----------------------" << endl;
}
return 0;
}
I want to know how to read above details in to the structure in the proper order.
You can use std::getline()
string readString;
if (file) {
while (!(file.eof())) {
getline(file,readString); // Read the column headers
for (int i = 0; i <= 7; i++) {
getline(file,limit[i].name,','); // ',' is the separator
getline(file,limit[i].nickName,',');
getline(file,limit[i].phoneNumber,',');
getline(file,limit[i].carrier,',');
getline(file,limit[i].address); // Read until the end of the line
}
}
}
I have to mention that I didn't test it so it might need some arrangements.

How to open and read a file based on user input c++

I have an assignment that wants me to write a program that reads a text file, then outputs a modified version of that file using a version of Ceasar cipher that shifts the characters of the file that the user calls based on the shift amount that they input. For example if my file reads "hi" and they shift it by 1 it should read "ij". But when I run the program it doesnt recognize when I call in1 or out1 and I just get an error message. Can anyone help me figure out what I'm doing wrong or offer any advice on how to move forward? Thank you in advance!
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cctype>
using namespace std;
int main()
{
//Declare user variables
int shift, file1chars = 0;
char filename[25];
ifstream in1;
ofstream out1;
do
{
in1.clear(); //clear status flags
//Prompt user to enter name of input file and amount of shift
cout << "Please enter the name of the input file." << endl;
cout << "Filename: ";
cin >> filename;
//Open file name
in1.open(filename);
//Error message if no file
if (!in1)
cout << "That is not a valid file. Try again\n";
} while (!in1);
do
{
out1.clear(); //clear status flags
//prompt user to input out file
cout << "Please enter the name of the output file." << endl;
cout << "Filename: ";
cin >> filename;
out1.open(filename);
//Error message if no file
if (!out1)
cout << "That is not a valid file. Try again\n";
} while (!out1);
//write some code to the input file
in1 >> "hi"
//write the integers in a different order to the output file
out1 << //idk where to go from here to initiate shift
//prompt user to enter shift
cout << "Please intput the shift amount: ";
cin >> shift;
cout << "Processing complete" << endl;
//Call file (?)
//Tell user file input is complete and is now printing statistics
cout << "\nShifted input file Complete. Now printing statistics " << endl;
//Show statistics for file
cout << "\nStatistics for file: " << filename << endl;
cout << "------------------------------------------------";
//Show characters in file and stats before shift
cout << "\n\nTotal # of characters in file: " << file1chars << endl;
cout << "Statistics before shift: " << endl;
//Show file before shift
//Show user stats after shift
cout << "\nStatistics after shift: " << endl;
//File after shift
//Close files
out1.close();
in1.close();
return 0;
}
Instead of looking at your code for line by line to see where the problem(s) could be, I ask you to think about your requirements and write code that expresses the intent as closely as possible. Create functions that follow the intended functionality.
Get the input file name.
Get the output file name.
Read the contents of the input file.
Transform the contents of the input file to create the output string.
Write the output string to the output file.
In pseudo code,
int main()
{
infile = get_input_filename()
outfile = get_output_filename()
contents = get_file_contents(infile)
output = transform_input(contents)
write_output(outfile, output)
}
Convert that to C++ code:
// Declare the functions.
std::string get_input_filename();
std::string get_output_filename();
std::string get_file_contents(std::string const& infile)
std::string transform_input(std::string const& contents)j
void write_output(std::string const& outfile, std::string const& output);
// Use them in main.
int main()
{
std::string infile = get_input_filename();
std::string outfile = get_output_filename();
std::string contents = get_file_contents(infile);
std::string output = transform_input(contents);
write_output(outfile, output);
}
// Implement the functions.
std::string get_input_filename()
{
std::string filename;
cout << "Please enter the name of the input file." << endl;
cout << "Filename: ";
cin >> filename;
return filename;
}
std::string get_output_filename()
{
std::string filename;
cout << "Please enter the name of the output file." << endl;
cout << "Filename: ";
cin >> filename;
return filename;
}
std::string get_file_contents(std::string const& infile)
{
std::ifstream inf(infile);
std::string contents;
int c;
while ( (c = inf.get()) != EOF )
{
contents += c;
}
return contents;
}
std::string transform_input(std::string const& contents)
{
std::string res;
// Do the needful to transform contents to res.
return res;
}
void write_output(std::string const& outfile, std::string const& output)
{
std::ofstream outf(outfile);
outf.write(output.c_str(), output.size();
}
If you are able to use a class or struct and functions I would propose something like this:
main.cpp
#include <string>
#include <iostream>
#include <fstream>
#include "CaesarShift.h"
int main() {
std::string filename;
std::cout << "Please enter the name of the input file. ";
std::cin >> filename;
std::ifstream fileIn;
std::string text;
fileIn.open( filename );
if ( !fileIn.is_open() ) {
std::cout << "Failed to open file: " << filename << "." << std::endl;
}
fileIn >> text;
fileIn.close();
CaesarText caesarText;
caesarText.addText( text );
std::cout << "Contents of the Caesar Text before peforming a Caesar Shift:\n"
<< caesarText << std::endl;
int amount = 0;
std::cout << "Please enter the amount to shift the text ";
std::cin >> amount;
std::cout << "Now performing the Caesar Shift: " << std::endl;
caesarShift( caesarText, amount );
std::cout << "Caesar Text after performing a Caesar Shift:\n"
<< ceasarText << std::endl;
std::ofstream fileOut;
fileOut.open( std::string( "shifted_" + filename ) );
if ( !fileOut.is_open() ) {
std::cout << "Failed to open shifted_" << filename << std::endl;
}
// Uncomment to print original text to file otherwise only modified text will be printed.
// fileOut << caesarText.originalText() << std::endl;
fileOut << caesarText.shiftedText() << std::endl;
fileOut.close();
system( "PAUSE" );
return 0;
}
CaesarShift.h
#ifndef CAESAR_SHIFT_H
#define CAESAR_SHIFT_H
class CaesarText {
std::string _originalText;
std::string _shiftedText;
public:
caesarText() = default;
explicit CeasarText( const std::string& text ) :
_originalText( text ) {}
void addText( const std::string& text ) {
_originalText = text;
}
std::string originalText() const {
return _originalText;
}
std::string shiftedText() const {
return _shiftedText;
}
friend void caesarShift( caesarText& c, int amount );
friend std::ostream& operator<<( std::ostream& out, const caesarText& ceasarText );
};
#endif // !CAESAR_SHIFT_H
CaesarShift.cpp
#include "CaesarShift.h"
#include <string>
#include <iostream>
#include <algorithm>
// Overloaded ostream operator
std::ostream& operator<<( std::ostream& o, const CaesarText& c ) {
o << "Original Text: " << c._originalText << "\n";
o << "Shifted Text: " << c._shiftedText << "\n";
return o;
}
// public friend function (visible in main) not actually a part of the class
// but performs operations on it.
// To perform the Caesar Shift here are 3 possible variations of implementing the same task.
void caesarShift( Caesar Text& text, int amount ) {
// Bound amount to the number of characters in the alphabet
// the same value used in any of the three variations below.
amount %= 26;
// Older c++ style loop.
/*for ( std::size_t i = 0; i < text._originalText.length(); i++ ) {
char c = text._originalText[i] + amount;
text._shiftedText += c;
}*/
// Modern C++ style loop
/*for ( auto& c : text._originalText ) {
text._shiftedText += c + amount;
}*/
// std::transform( s1.begin, s1.end, back_inserter( s2 ), lamda as predicate );
/*std::transform( text._originalText.begin(), text._originalText.end(),
std::back_inserter( text._shiftedText ),
[amount]( unsigned char c ) -> unsigned char { return c + amount; }
);*/
}
As for the 3 different variations of performing the Caesar Shift you can just uncomment the appropriate block section.

Floating Point Exception while reading from file

the program should read from 2 files (author.dat and citation.dat) and save them into a map and set;
first it reads the citationlist without problem, then it seems to properly read the authors and after it went through the whole list (author.dat) a floating point exception arises .. can't quite figure out why
seems to happen in author.cpp inside the constructor for authorlist
author.cpp:
#include <fstream>
#include <iostream>
#include "authors.h"
using namespace std;
AuthorList::AuthorList(char *fileName) {
ifstream s (fileName);
int idTemp;
int nrTemp;
string nameTemp;
try {
while (true){
s >> idTemp >> nrTemp >> nameTemp;
cout << idTemp << " " << nrTemp << " " << nameTemp << " test_string";
authors.insert(std::make_pair(idTemp,Author(idTemp,nrTemp,nameTemp)));
if (!s){
cout << "IF-CLAUSE";
throw EOFException();
}
cout << "WHILE-LOOP_END" << endl;
}
} catch (EOFException){}
}
author.h:
#ifndef CPP_AUTHORS_H
#define CPP_AUTHORS_H
#include <iostream>
#include <map>
#include <string>
#include "citations.h"
class Author {
public:
Author (int id, int nr, std::string name) :
articleID(id),
authorNR(nr),
authorName(name){}
int getArticleID() const {
return articleID;
}
std::string getAuthorName() const {
return authorName;
}
private:
int articleID;
int authorNR;
std::string authorName;
};
class AuthorList {
public:
AuthorList(char *fileName);
std::pair<std::multimap<int,Author>::const_iterator, std::multimap<int,Author>::const_iterator> findAuthors(int articleID) {
return authors.equal_range(articleID);
}
private:
std::multimap<int,Author> authors;
};
#endif //CPP_AUTHORS_H
programm.cpp:
#include <iostream>
#include <cstdlib>
#include "citations.h"
#include "authors.h"
#include "authorCitation.h"
using namespace std;
int main(int argc, char *argv[]){
CitationList *cl;
AuthorList *al;
//check if argv array has its supposed length
if (argc != 4){
cerr << "usage: programm article.dat citation.dat author.dat";
return EXIT_FAILURE;
}
//inserting citation.dat and author.dat in corresponding lists (article.dat not used)
cl = new CitationList(argv[2]);
al = new AuthorList(argv[3]);
try {
AuthorCitationList *acl;
acl->createAuthorCitationList(al,cl);
acl->printAuthorCitationList2File("authorcitation.dat");
} catch (EOFException){
cerr << "something went wrong while writing to file";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
All files:
https://drive.google.com/file/d/0B734gx5Q_mVAV0xWRG1KX0JuYW8/view?usp=sharing
I am willing to bet that the problem is caused by the following lines of code:
AuthorCitationList *acl;
acl->createAuthorCitationList(al,cl);
You are calling a member function using an uninitialized pointer. I suggest changing the first line to:
AuthorCitationList *acl = new AuthorCitationList;
Add any necessary arguments to the constructor.
While you are at it, change the loop for reading the data also. You have:
while (true){
s >> idTemp >> nrTemp >> nameTemp;
cout << idTemp << " " << nrTemp << " " << nameTemp << " test_string";
authors.insert(std::make_pair(idTemp,Author(idTemp,nrTemp,nameTemp)));
if (!s){
cout << "IF-CLAUSE";
throw EOFException();
}
cout << "WHILE-LOOP_END" << endl;
}
When you do that, you end up adding data once after the end of line has been reached. Also, you seem to have the last line in the wrong place. It seems to me that it should be outside the while loop.
You can use:
while (true){
s >> idTemp >> nrTemp >> nameTemp;
// Break out of the loop when reading the
// data is not successful.
if (!s){
cout << "IF-CLAUSE";
throw EOFException();
}
cout << idTemp << " " << nrTemp << " " << nameTemp << " test_string";
authors.insert(std::make_pair(idTemp,Author(idTemp,nrTemp,nameTemp)));
}
cout << "WHILE-LOOP_END" << endl;
You can simplify it further by using:
while (s >> idTemp >> nrTemp >> nameTemp){
cout << idTemp << " " << nrTemp << " " << nameTemp << " test_string";
authors.insert(std::make_pair(idTemp,Author(idTemp,nrTemp,nameTemp)));
}
cout << "WHILE-LOOP_END" << endl;

C++ Vector of Struct using push_back

This is an assignment for a course that I am having problems with. Until now I thought I was fairly familiar with vectors in C++. This program is supposed to take a file from the user calculate the users pay then spit back out in a nice table all the information relevant.
It must contain a vector of struct and I must use push_back. I get two errors that I cannot figure out at this moment. In the for loop at the end of main() it tells me a reference type of vector cannot be initialized with Employee. The two functions after ward tell me that I for example .HoursWorked is not a member of the struct.
I tried looking around other questions for help but they all mentioned not using pointers which I'm 100% positive there are no pointers in my program. The txt file I am using for testing the program looks as follows:
John Smith 123-09-8765 9.00 46 F
Kevin Ashes 321-09-8444 9.50 40 F
Kim Cares 131-12-1231 11.25 50 P
Trish Dish 141-51-4564 7.52 24 P
Kyle Wader 432-12-9889 5.75 48 F
Code:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <vector>
using namespace std;
struct Employee
{
string name;
string ssn;
double hourlyWage;
double HoursWorked;
char status;
double straightTimePay;
double overTimePay;
double netPay;
};
void calculatePay(vector<Employee>& buisness);
void displayEmployee(vector<Employee> buisness);
int main()
{
vector<Employee> buisness;
string fileName, line;
ifstream inFile;
stringstream ss;
cout << "Please input the file name to read: ";
cin >> fileName;
inFile.open(fileName);
if (!inFile)
{
cout << "Cannot open file " << fileName << " Aborting!" << endl;
exit(1);
}
int index = 0;
string firstName, lastName;
getline(inFile, line);
while (!inFile.eof())
{
if (line.length() > 0)
{
ss.clear();
ss.str(line);
buisness.push_back;
ss >> firstName >> lastName;
buisness[index].name = firstName + " " + lastName;
ss >> buisness[index].ssn;
ss >> buisness[index].hourlyWage >> buisness[index].HoursWorked;
ss >> buisness[index].status;
index++;
}
getline(inFile, line);
}
inFile.close();
cout << "The information of the buisness:" << endl;
cout << setw(20) << "Name" << setw(15) << "SSN" << setw(12) << "Hourly Wage";
cout << setw(14) << "Hours Worked" << setw(18) << "Straight Time Pay";
cout << setw(14) << "Over Time Pay" << setw(6) << "Status" << setw(10) << "Net Pay" << endl;
for (index = 0; index < buisness.size(); index++)
{
calculatePay(buisness[index]);
displayEmployee(buisness[index]);
}
return 0;
}
void calculatePay(vector<Employee>& buisness)
{
if (buisness.HoursWorked <= 40)
{
buisness.straightTimePay = buisness.hourlyWage * buisness.HoursWorked;
buisness.overTimePay = 0;
}
else
{
buisness.straightTimePay = buisness.hourlyWage * 40;
buisness.overTimePay = buisness.hourlyWage * 1.5 * (buisness.HoursWorked - 40);
}
buisness.netPay = buisness.straightTimePay + buisness.overTimePay;
if (buisness.status == 'F')
buisness.netPay -= 10;
}
void displayEmployee(vector<Employee> buisness)
{
int precisionSetting = cout.precision();
long flagSettings = cout.flags();
cout.setf(ios::fixed | ios::showpoint);
cout.precision(2);
cout << setw(20) << buisness.name << setw(15) << buisness.ssn << setw(12) << buisness.hourlyWage;
cout << setw(14) << buisness.HoursWorked << setw(18) << buisness.straightTimePay;
cout << setw(14) << buisness.overTimePay << setw(6) << buisness.status << setw(10) << buisness.netPay << endl;
cout.precision(precisionSetting);
cout.flags(flagSettings);
}
At the very least.. You have the line:
calculatePay(buisness[index]);
So clearly we all calling a function calculatePay and we're passing it an Employee.
But your function prototype says that it takes a std::vector<Employee>. You probably intended for the functions to take Employee & instead.
You should call vector push_back with the element to put in:
Employee employee;
// assign values to employee
ss << employee.ssn;
ss << employee.name;
business.push_back(employee);
Although the compiler error logs seem tedious, but you can almost always get enough information from the error logs. Compiling under gcc 4.2.1, the error logs says :
error: invalid initialization of reference of type ‘std::vector<Employee, std::allocator<Employee> >&’ from expression of type ‘Employee’ on the line of calling method calculatePay(). We can infer that you passed Employee to and function which want an vector of Employee as parameter. You can fix this by change calculatePay(vector<Employee>& buisness) to calculatePay(Employee& buisness). And that will fix error: ‘class std::vector<Employee, std::allocator<Employee> >’ has no member named ‘HoursWorked’

Trying to make string array passed through methods C++

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.