C/C++ Implement C++ Program: Guide & Examples

  • Thread starter Thread starter Nusc
  • Start date Start date
  • Tags Tags
    Program
AI Thread Summary
The discussion revolves around a C++ program designed to read employee data from a file and manage employee records. The program encounters several issues, including a compiler error related to the placement of curly braces and problems with reading and displaying employee data, particularly the join and leave dates. Users express confusion about the syntax and functionality of the `GetData` function, which is intended to read employee information into a vector of `Employee` structs. There are also concerns about infinite loops during data entry and the proper use of string comparison methods. Suggestions include using `infile.getline()` for reading lines, utilizing `strcmp` for string comparisons, and emphasizing the importance of correctly accessing struct members. The conversation highlights the need for clarity in data parsing and the correct implementation of C++ features to avoid runtime errors.
Nusc
Messages
752
Reaction score
2
C++

I'm supposed to read in the file:

Joe Bloggs 10 June 2002 21 Sept 2004 48524
Jane Doe 6 Feb 2004 0 nomonth 0 52595

#include <string>
#include <fstream>
#include <vector>
#include <iostream>
using namespace std;

//user-defined types
struct datetype
{
int day;
string month;
int year;
};

struct Employee
{
string first;
string last;
datetype join;
datetype left;
int salary;

};

// prototypes
void GetData(vector <Employee>&a, string filename);
void AddEmployee(vector<Employee>&a);
void ListCurrent(const vector <Employee>&a);
int main();
//I get the following compiler error
//emp.cc:30: error: expected unqualified-id before '{' token
//emp.cc:30: error: expected `,' or `;' before '{' token
{ // <------------ on this line

string filename;
vector <Employee> a;
cout <<"Please enter your filename:"<< endl;
cin >> filename;

GetData(a,filename);
char choice;
do
{
cout <<"What do you wish to do with the database?"<<endl;
cout <<"Input the relevant letter: Options are:"<< endl;
cout <<"(a) Add an employee to the file" << endl;
cout <<"(b) List the current employees"<< endl;
cout <<"(c) Quit the program"<< endl;
cin >> choice;
cout <<"You have entered:"<< choice << endl;

switch(choice)
{
case('a'):
AddEmployee(a);
break;

case('b'):
ListCurrent(a);
break;
case('c'):
{
cout <<"Program ending"<< endl;
}
}
}while(choice != 'c');
return 0;
}
//I'm supposed to read in a file but I'm not sure whether I use struct or a vector after the while loop.
void GetData(vector <Employee>&a,string filename)
{
ifstream infile(filename.c_str());
if(infile.fail())
{
cout << "Could not find existing file."<< endl;
exit(0);
}
while(!infile.eof());

infile >>
infile >>
infile >>
infile >>
infile >>
infile >>
}
a.push_back( ? )
infile.close();
}

}

void AddEmployee(vector<Employee>&a)
{
Employee b;
cout <<"Please enter your employee's first and last name:" << endl;
cin >> b.first >> b.last;
cout <<"Please enter your employee's joining date and leaving date (day month year)" << endl;
cin >> b.join.day >> b.join.month >> b.join.year >> b.left.day >> b.left.month >> b.left.year;
cout <<"Please enter your employee's salary:" << endl;
cin >> b.salary;
a.push_back(b);
cout <<"New employee successfully added." << endl;
}
//This function is supposed to list the current employees rather than the list of employees but I don't know how to do that.
void ListCurrent(const vector <Employee>&a)
{
cout <<"Here is a list of names of your employees" << endl;
for (int i = 0; i<a.size();i++)
{
cout<<a.at(i).last<<", "<<a.at(i).first<< endl;
}
}

Can anyone please help me?
 
Last edited:
Technology news on Phys.org
As far as I know, for things like main() and while loops, the syntax is:

Code:
main()
{
  //TODO:
}

while(condition)
{
  //TODO statements
}

instead of the semi-colon you put. Secondly now, do you know exactly what is passed when you type in "infile >>"? If I recall correctly, it is the buffer to the entire file. What format is the file? How is the information delimited? Would you consider using "infile.getline"?
 
I'm passing in some arbitrarytext file.

I'm supposed to read in the file:

Joe Bloggs 10 June 2002 21 Sept 2004 48524
Jane Doe 6 Feb 2004 0 nomonth 0 52595
 
If you would like to simply just print out the entire text file, then you can just pass the entire file into a string variable. Then print that.

If however, you want to extract certain information from your text file, then welcome to the world of text parsing. Say your file has text as such:

Code:
Joe Bloggs 10 June 2002 21 Sept 2004 48524
Jane Doe 6 Feb 2004 0 nomonth 0 52595

You can read in each line by using "infile.getline()". See MSDN for more info on how to use it. Once you have one line in a char array, then you can process it. The creativity in how to do this is up to you. For example to get the first name:

Code:
char[20] csFirstname;
i = 0;

While (input[i] != '\n') Do
  If (input[i] == ' ')
    temp[i] = '\0';
    strcpy(csFirstname, temp);
  Else
    temp[i] = input[i];
  Increase i by 1;
EndWhile
 
Okay I got my progra to run. Now my problem is listing the current employees:

void ListCurrent(const vector <Employee>&a)
{
const string b = "nomonth";

cout <<"Here is a list of names of your employees:" << endl;

for(int i=0; i<a.size();i++)
{
if(a.at(i).join.month == b)
cout<<a.at(i).last<<", "<<a.at(i).first<<endl;
}
}

Won't display anything. I believe it has to do with:
if(a.at(i).join.month == b)
 
Actually. My program won't read in the dates left ad dates joined.

Does anyone know why?
 
You might want to use string functions from the string library, such as "strcmp" instead of a pure if (a == "stringb"). This direct string comparison is always unsafe to use.

Edit:
In fact, since you are already using the STL string implementation, you should consistently use the member methods of this string class. There are many many useful string operations already implemented. See MSDN documention on "basic_string class".

For example:

string mystring
if (mystring.compare("teststring"))
printf("strings match\n")
 
Last edited:
I have absolutely no idea what you're talking about.

I just need to find out how to read the datatype join and the datatype left
 
Nusc said:
I have absolutely no idea what you're talking about.

I just need to find out how to read the datatype join and the datatype left

Weren't you the one to define those structs yourself? You access the members just like in any other struct.

Code:
//user-defined types
struct datetype
{
int day;
string month;
int year;
};

struct Employee
{
string first;
string last;
datetype join;
datetype left;
int salary;

};
 
  • #10
Here is my latest version:
#include <string>
#include <fstream>
#include <vector>
#include <iostream>
using namespace std;

//user-defined types
struct datetype
{
int day;
string month;
int year;
};

struct Employee
{
string first;
string last;
datetype join;
datetype left;
int salary;

};

// prototypes
void GetData(vector <Employee>&a, string filename);
void AddEmployee(vector<Employee>&a);
void ListCurrent(const vector <Employee>&a);


int main()
{

string filename;
vector <Employee> a;
cout <<"Please enter your filename:"<< endl;
cin >> filename;

GetData(a,filename);
char choice;
do
{
cout <<"What do you wish to do with the database?"<<endl;
cout <<"Input the relevant letter: Options are:"<< endl;
cout <<"(a) Add an employee to the file" << endl;
cout <<"(b) List the current employees"<< endl;
cout <<"(c) Quit the program"<< endl;
cin >> choice;
cout <<"You have entered:"<< choice << endl;

switch(choice)
{
case('a'):
AddEmployee(a);
break;

case('b'):
ListCurrent(a);
break;
case('c'):
{
cout <<"Program ending"<< endl;
}
}
}while(choice != 'c');
return 0;
}

void GetData(vector <Employee>&a,string filename)
{
Employee tmp;
ifstream infile(filename.c_str());
if(infile.fail())
{
cout << "Could not find existing file."<< endl;
exit(0);
}


while(!infile.eof())
{

infile >> tmp.first >> tmp.last;
infile >> tmp.join.day >> tmp.join.month >> tmp.join.year;
infile >> tmp.left.day >> tmp.left.month >> tmp.left.year;
infile >> tmp.salary;
a.push_back(tmp);

}
}

void AddEmployee(vector<Employee>&a)
{
Employee b;
cout <<"Please enter your employee's first and last name:" << endl;
cin >> b.first >> b.last;
cout <<"Please enter your employee's joining date and leaving date (day month year)" << endl;
cin >> b.join.day >> b.join.month >> b.join.year >> b.left.day >> b.left.month >> b.left.year;
cout <<"Please enter your employee's salary:" << endl;
cin >> b.salary;
a.push_back(b);
cout <<"New employee successfully added." << endl;
}

void ListCurrent(const vector <Employee>&a)
{
// const string b = "nomonth";

cout <<"Here is a list of names of your employees:" << endl;

for(int i=0; i<a.size();i++)
{
// if(a.at(i).join.month == b)
cout<<a.at(i).last<<", "<<a.at(i).first<<endl;
}
}



My getdata function doesn't read in the join date and the date left.
I don't know why. Hence I cannot add an employee's join date or date left without my program crashing. How do I fix this? Nor can I list the current employees. The commented stuff in the last function was my attempt display the current users but because it can't read in the structs it won't display anything.
 
  • #11
There doesn't seem to be a problem with your GetData function, your ListCurrent function just doesn't print out this information. You only print out the first and last names. The join dates are in a.at(i).join.day, etc.

for(int i=0; i<a.size();i++)
{
// if(a.at(i).join.month == b)
cout<<a.at(i).last<<", "<<a.at(i).first<<endl;
}
 
  • #12
I'm already aware of that. My question is, how do I fix it.
 
  • #13
I'm just ultimately surprised that being able to write all of that (rest of your program), you don't know what to do. And I'm sure you understand that nobody on this forum is getting paid to solve problems for other people. We're here on our own good-will and ultimately we want to help others learn and learn new things ourselves.

Your for-loop is doing its job, you just need to print everything you want, for example try:

Code:
for(int i=0;i<a.size();i++)
{
  cout << a.at(i).last << ", " << a.at(i).first << ", " << a.at(i).join.day << endl;
}
 
  • #14
I appreciate the help.

There are employees in the list that have left the company and there are those still currently working for it.

My task is to list the current workers.
The commented stuff in the last function was my attempt to do that but once i run the program it won't display anything.

The code you provided does exactly what I written, which is not what I"m looking for.

If I try and add an employee my program goes into an infinite loop once I add the dates joined and dates left.

This is just a practice exam problem
 
Last edited:
  • #15
Nusc said:
I appreciate the help.

There are employees in the list that have left the company and there are those still currently working for it.

My task is to list the current workers.
The commented stuff in the last function was my attempt to do that but once i run the program it won't display anything.

The code you provided does exactly what I written, which is not what I"m looking for.

If I try and add an employee my program goes into an infinite loop once I add the dates joined and dates left.

This is just a practice exam problem

Could you provide an example of your interaction with the program that causes it to enter an infinite loop?

Cheers,
Tim
 
  • #16
could you provide indentation or use the
Code:
block provide by the forum?
also with the stl::vector u can use a rather than a.at.

And as mentioned aboveuse strcmp.

look at hte string function c_str() i think it is. or cstr().
 
Last edited:
  • #17
I'm using cygwin, how do i copy and paste the terminal? Because it won't let e select anything.

Actually I am wrong, nevermind the infinite loop./

but about displaying the current users...stil a problem.


the c_str thing is not important.
 
Last edited:
  • #18
ah but c_str is important because it helps you control the output with printf rather than cout So you can see if waht is being stored is right and then go back to using cout..

also with c_str you can also use strcmp.

Look for you cygwin directory under windows...then find the home directory and from there your project directory and use notepad or wordpad.

or use the
Code:
brackets in the utility on this website.
 
  • #19
neurocomp2003 said:
ah but c_str is important because it helps you control the output with printf rather than cout So you can see if waht is being stored is right and then go back to using cout..
What can you do with the C streaming library that you cannot do with the C++ streaming library?

also with c_str you can also use strcmp.
And what's wrong with the == operator (for std::strings)?

Look for you cygwin directory under windows...then find the home directory and from there your project directory and use notepad or wordpad.
You can launch notepad from cygwin. I find that much easier. :smile:
 
  • #20
you can probably do everything with the C++ library with C library but formatting i have found to be a big pain using C++ that's why i stick to printf's when debugging. When I'm ready to produce results i would switch to C++ plus overloading the << and >> operators are wonders but for debugging purposes(that is without using the debugger) i like the printf. Nothing like %+-10.5f or %p, or %10s

...also apparently his/her code isn't working which the other poster said wasn't most of his functions but that one line where he was doing a string compare with ==...using strcmp is another way to compare the string...but if he had the == working in the first place he probably wouldn't have needed help.

lol you can launch notepad from cygwin? ...never knew that...i find it better to know where the directory is...i'm not much of a command line user. but outat curiosity how do you run notepad?
 
Last edited:
  • #21
neurocomp2003 said:
you can probably do everything with the C++ library with C library but formatting i have found to be a big pain using C++ that's why i stick to printf's when debugging. When I'm ready to produce results i would switch to C++ plus overloading the << and >> operators are wonders but for debugging purposes(that is without using the debugger) i like the printf. Nothing like %+-10.5f or %p, or %10s

Code:
printf( "Address is %p", ptr );

printf( "%+-10.5f", fNum );

printf( "%10s", str );

Code:
cout << "Address is " << ptr;

cout << setw(10) << left << showpos << fixed << setprecision(5) << fNum;

cout << setw(10) << str.c_str();
One can read everything from left to right as it would appear, more verbose such that much easier to work out and remember what each manipulation means. I'll stick to cout with my C++ codes. :smile:
 
  • #22
boo too much typing...
printf( "Address is %p; \n%+-20.5f; \n%10s", ptr,fNum, str );

cout << "Address is " << ptr << ";"<<endl
<< setw(20) << left << showpos << fixed << setprecision(15) << fNum<< ";"<<endl
<< setw(10) << str.c_str();

to each his own. (i don't like using too much words in my code...i think more in terms of math symbols than words...all about abbreviating words)

its almost like typing position=velocity*time; vs x=v*t;
 
Last edited:
Back
Top