Implement C++ Program: Guide & Examples

  • Thread starter Nusc
  • Start date
  • Tags
    Program
In summary, this program involves reading in a text file and using structs and vectors to store and manipulate data about employees. It allows for adding new employees, listing current employees, and quitting the program. There may be issues with reading in dates and comparing strings in the program.
  • #1
Nusc
760
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
  • #2
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"?
 
  • #3
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
 
  • #4
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
 
  • #5
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)
 
  • #6
Actually. My program won't read in the dates left ad dates joined.

Does anyone know why?
 
  • #7
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:
  • #8
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
 
  • #9
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:

1. What is C++ and why is it useful?

C++ is a high-level programming language that was developed in the 1980s as an extension of the C language. It is widely used in software development for its efficiency, flexibility, and ability to directly access hardware resources. It is also used in developing operating systems, video games, and other high-performance applications.

2. How do I install a C++ compiler?

To implement C++ programs, you will need a C++ compiler. Popular options include GCC, Clang, and Visual C++. These can be downloaded and installed from their respective websites. You can also use an integrated development environment (IDE) such as Visual Studio, Code::Blocks, or Eclipse, which includes a compiler and other tools for coding and debugging.

3. What are the basic syntax and structure of a C++ program?

A C++ program is made up of functions, which are blocks of code that perform specific tasks. Every program must have a main() function, which is where the program begins executing. The basic structure of a C++ program is as follows:

  1. #include <iostream> // include input/output library
  2. using namespace std; // use standard namespace
  3. int main() { // main function
  4. // program statements
  5. return 0; // return statement
  6. }

4. How do I write and execute a basic C++ program?

To write a basic C++ program, you can use a text editor such as Notepad or a specialized code editor such as Visual Studio Code. Save the file with a .cpp extension, which indicates that it is a C++ source file. Then, use a C++ compiler to compile the code into an executable file. This can be done through the command line or through the IDE. Finally, run the executable file to see the output of your program.

5. What are some common data types in C++?

C++ supports several data types, including integers, floating-point numbers, characters, booleans, and strings. Integers are used for whole numbers, while floating-point numbers are used for numbers with decimal points. Characters represent individual letters or symbols, and booleans have a value of either true or false. Strings are used to store sequences of characters and are enclosed in double quotes. There are also more advanced data types, such as arrays, pointers, and structures, which allow for more complex data manipulation.

Similar threads

  • Programming and Computer Science
Replies
12
Views
1K
Replies
10
Views
958
  • Programming and Computer Science
Replies
5
Views
2K
  • Programming and Computer Science
Replies
5
Views
1K
  • Programming and Computer Science
2
Replies
66
Views
4K
  • Programming and Computer Science
Replies
3
Views
3K
  • Programming and Computer Science
Replies
4
Views
5K
  • Programming and Computer Science
Replies
8
Views
2K
  • Programming and Computer Science
Replies
6
Views
8K
  • Programming and Computer Science
3
Replies
89
Views
4K
Back
Top