On-line: гостей 0. Всего: 0 [подробнее..]
Программисты всех стран, объединяйтесь!

АвторСообщение



ссылка на сообщение  Отправлено: 08.10.12 09:53. Заголовок: Ifstream & ofstream


employee.cpp

#include "employee.h"

void readRecord(Employee *theEmployee , int &size){

ifstream inFile;

inFile.open( "employee.txt" );

if( inFile.fail() )
cout << "Unable to obtain Employee Data ! " << endl
<< "New Database created !" << endl << endl;;

if( inFile.is_open() ){
/* while( !inFile.eof() ){
getline( inFile , theEmployee[size].EmployeeID );
getline( inFile , theEmployee[size].EmployeeName );
getline( inFile , theEmployee[size].EmployeeDepartment );
getline( inFile , theEmployee[size].EmployeeDOB );
getline( inFile , theEmployee[size].EmployeeAddress );
inFile >> theEmployee[size].EmployeeWorkHours;
inFile >> theEmployee[size].PayRate;
inFile >> theEmployee[size].totalSalary;
size++;
}*/
inFile >> size;
inFile.ignore(1, ':');
cout << size ;
cin.get();
for (int i = 0 ; i < size ; ++i)
{
getline( inFile , theEmployee.EmployeeID );
getline( inFile , theEmployee.EmployeeName );
getline( inFile , theEmployee.EmployeeDepartment );
getline( inFile , theEmployee.EmployeeDOB );
getline( inFile , theEmployee.EmployeeAddress );
inFile >> theEmployee.EmployeeWorkHours;
inFile >> theEmployee.PayRate;
inFile >> theEmployee.totalSalary;
inFile.ignore(1,':');
}
}
}

void addRecord(Employee *theEmployee , int &size){
ofstream outFile;

/*if( size > 1 ){
size = size - 1;
cout<<"Size: "<< size;
}*/
cout<<"Size: "<< size;
cout << "\nEnter Employee ID [Mix of Char & Integer] : ";
cin.ignore();
getline( cin,theEmployee[size].EmployeeID );

cout << "Enter Name : ";
getline( cin,theEmployee[size].EmployeeName );

cout << "Enter Employee Department : ";
getline( cin,theEmployee[size].EmployeeDepartment );

cout << "Date of birthday [dd/mm/yy] : ";
//cin.ignore();
getline( cin,theEmployee[size].EmployeeDOB );

cout << "Enter Address : ";
getline( cin,theEmployee[size].EmployeeAddress );

do{
cout << "Enter Work Hour : ";
cin >> theEmployee[size].EmployeeWorkHours;
if( theEmployee[size].EmployeeWorkHours < 1 ){
cout << "Invalid Input for Work Hours !" << endl;
}
}while( theEmployee[size].EmployeeWorkHours < 1 );

do{
cout << "Enter Pay Rate : ";
cin >> theEmployee[size].PayRate;
if( theEmployee[size].PayRate < 1 )
cout << "Invalid Input for Pay Rate !" << endl;
}while( theEmployee[size].PayRate < 1 );

theEmployee[size].totalSalary = theEmployee[size].EmployeeWorkHours * theEmployee[size].PayRate ;

/*size++;
if( size == 0 ){
size++;
}*/

outFile.open( "employee.txt" );
size++;
outFile << size << "\n" ;

for( int i = 0 ; i < size ; i++ ){
outFile << theEmployee.EmployeeID << endl << theEmployee.EmployeeName << endl
<< theEmployee.EmployeeDepartment << endl
<< theEmployee.EmployeeDOB << endl << theEmployee.EmployeeAddress
<< endl << theEmployee.EmployeeWorkHours << endl << theEmployee.PayRate
<< endl << theEmployee.totalSalary << ':' << endl;
}

outFile.close();
}

void displaySpecificEmployee(Employee *theEmployee , int &size){

string SpecificEmployeeID = "";
int foundIndex = 0;
bool found = 0;

system( "cls" );
cin.ignore();
cout << "\tSearch a particular employee's payroll " << endl
<< "-------------------------------------------------------" << endl << endl
<< "Enter Employee ID : ";


getline(cin,SpecificEmployeeID);

for( int i = 0 ; i < size ; i++ ){
if( theEmployee.EmployeeID==SpecificEmployeeID ){
found = true;
foundIndex = i;
}
}
cout<<"********"<<theEmployee[1].EmployeeID<<"********"<<endl;
if( found == true ){
cout << "Employee ID : " << theEmployee[foundIndex].EmployeeID << endl
<< "Employee Name : " << theEmployee[foundIndex].EmployeeName << endl
<< "Employee Department : " << theEmployee[foundIndex].EmployeeDepartment << endl
<< "Employee Date Of Birth : " << theEmployee[foundIndex].EmployeeDOB << endl
<< "Employee Address : " << theEmployee[foundIndex].EmployeeAddress << endl
<< "Employee Work Hours : " << theEmployee[foundIndex].EmployeeWorkHours << endl
<< "Employee Pay Rate : " << theEmployee[foundIndex].PayRate << endl
<< "Employee Salary : " << theEmployee[foundIndex].totalSalary << endl;
}
else
cout << "No Any Record found ! " << endl;

}


Спасибо: 0 
ПрофильЦитата Ответить
Ответов - 18 [только новые]





ссылка на сообщение  Отправлено: 08.10.12 09:54. Заголовок: main.cpp #include &..


main.cpp

#include "employee.h"

int main(){

Employee theEmployee[30];
int size = 0;
char choice;
char choice2;

readRecord( theEmployee , size );

cout << "1. Add an employee\n";
cout << "2. View employee record\n";
cout << "3. Modify employee record\n";
cout << "4. Delete Employee record\n";
cout << "5. Press q or Q to Exit\n";
cout << "\nPlease choose an item: ";
cin >> choice;

switch( choice ){
case '1':
addRecord(theEmployee , size);
break;
case '2':
system( "cls" );
cout << "1. Display a particular employee's payroll" << endl
<< "2. All Employees' payroll" << endl
<< "3. All Employees' payroll in a particular department" << endl << endl;

cout << "Enter Choice : ";
cin >> choice2;
switch( choice2 ){
case '1':
displaySpecificEmployee(theEmployee , size);
break;
}

case 'q':
break;
case 'Q':
cout << "\nProgram will be terminated now!" << endl;
getch();
return 0;
}

system( "pause" );
return 0;
}


Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 08.10.12 09:59. Заголовок: just need


now my question is..

why inside my data file.

while i when i save first record , its perfect.

so i keep save file m the error keep come out ( error : alien language )
example my "employee.txt" after i key in 3 record

3
ad123
jye
sales
13-10-1991
41,jalan
500
300
150000:

ad124
wendy
finance
1-5-1993
25
-9.25596e+061
-9.25596e+061:
ad125
hsien
12312
123
123
5000
200
1e+006:


Спасибо: 0 
Цитата Ответить



ссылка на сообщение  Отправлено: 08.10.12 13:36. Заголовок: I am sorry but I hav..


I am sorry but I have not understood the question. Could you repeat it?

Also this code is unclear.

if( inFile.is_open() ){
/* while( !inFile.eof() ){
getline( inFile , theEmployee[size].EmployeeID );
getline( inFile , theEmployee[size].EmployeeName );
getline( inFile , theEmployee[size].EmployeeDepartment );
getline( inFile , theEmployee[size].EmployeeDOB );
getline( inFile , theEmployee[size].EmployeeAddress );
inFile >> theEmployee[size].EmployeeWorkHours;
inFile >> theEmployee[size].PayRate;
inFile >> theEmployee[size].totalSalary;
size++;
}*/
inFile >> size;
inFile.ignore(1, ':');
cout << size ;
cin.get();

/* Here if I am not wrong size becomes equal to 1500 after reading

3
ad123
jye
sales
13-10-1991
41,jalan
500
300
150000:

And then you are trying in the loop to read 1501 records are not you?
*/

for (int i = 0 ; i < size ; ++i)
{
getline( inFile , theEmployee.EmployeeID );
getline( inFile , theEmployee.EmployeeName );
getline( inFile , theEmployee.EmployeeDepartment );
getline( inFile , theEmployee.EmployeeDOB );
getline( inFile , theEmployee.EmployeeAddress );
inFile >> theEmployee.EmployeeWorkHours;
inFile >> theEmployee.PayRate;
inFile >> theEmployee.totalSalary;
inFile.ignore(1,':');
}


Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 08.10.12 14:03. Заголовок: sorry sir ^^ i solve..


sorry sir ^^ i solve it , by using the

outFile.open( "employee.txt" , ios :: out ) <- method

hmm , but i not so clear when wan to use the ios :: out .

as my question required , it need me to store the file in binary , isn't mean ios ::binary?

if i insert the ios :: binary into
outFile.open( "employee.txt" , ios :: out || ios :: binary )

inside my textfile will be stick up together with each details , no any endl or spaces between them

Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 08.10.12 14:13. Заголовок: Take into acccount t..


Take into acccount that the following code is also unclear

 switch( choice ){  
case '1':
addRecord(theEmployee , size);
break;
case '2':
system( "cls" );
cout << "1. Display a particular employee's payroll" << endl
<< "2. All Employees' payroll" << endl
<< "3. All Employees' payroll in a particular department" << endl << endl;

cout << "Enter Choice : ";
cin >> choice2;
switch( choice2 ){
case '1':
displaySpecificEmployee(theEmployee , size);
break;
}

case 'q':
break;
case 'Q':
cout << "\nProgram will be terminated now!" << endl;
getch();
return 0;
}

In this code snip you have not break for label case 2: of the outer switch statement.

Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 08.10.12 18:27. Заголовок: ya i know.. i havent..


ya i know.. i havent update the code , all having fine now, but in case i wan store the file in binary format . how should i to do?
as the question required me to do so..

if i insert ios:: binary into my outfile .
i getting some error with it.. all my outfile variable will be stick together

how should i to solve it?

Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 09.10.12 00:20. Заголовок: You should use funct..


You should use functions read and write for a file used in the binary mode.

Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 09.10.12 12:59. Заголовок: u mean using ios :: ..


u mean using ios :: in || ios :: out || ios :: binary ? use in my outFile? or?

Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 09.10.12 16:34. Заголовок: I mean that if you u..


I mean that if you use the binary mode of a stream then you should use functions read and write. Otherwise in the text mode some data will be interpreted as control symbols.

Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 09.10.12 18:13. Заголовок: can provide the exam..


can provide the example ?
sorry ya

Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 09.10.12 23:42. Заголовок: Here is an example o..


Here is an example of using functions write and read with a binary file stream.

 #include <iostream> 
#include <fstream>

int main()
{
{
const char *fname = "Binary.dat";
std::ofstream fout( fname, std::ios::out | std::ios::binary );

if (!fout )
{
std::cout << fname << ": open file error" << std::endl;
std::exit( 1 );
}

struct
{
int x;
double y;
char s[20];
} data = { 10, 15.0, "This is a test" };

fout.write( reinterpret_cast<const char *>( &data ), sizeof( data ) );
}

{
const char *fname = "Binary.dat";
std::ifstream fin( fname, std::ios::in | std::ios::binary );

if (!fin )
{
std::cout << fname << ": open file error" << std::endl;
std::exit( 1 );
}

struct
{
int x;
double y;
char s[20];
} data;

fin.read( reinterpret_cast<char *>( &data ), sizeof( data ) );

std::cout << "data.x = " << data.x
<< ", data.y = " << data.y
<< ", data.s = " << data.s << std::endl;
}

return 0;
}


Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 10.10.12 15:42. Заголовок: i know how the binar..


i know how the binary should put ..
but the problem is when i put ios :: binary .

my data inside the txtfile after ofstream .
all data will be stick together

example :
ofstream Outfile;

Outfile.open("employee.txt" , ios :: out || ios ::binary );
Outfile << theEmployeeID << theEmployeeName << theEmployeeDOB;

if i didn't insert the binary code . my file save properly.
after i insert the binary . my file will become like this

AD125CHIRSJYE13-10-1991

all data will be stick together .

why d?

Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 10.10.12 16:24. Заголовок: No, you are wrong. T..


No, you are wrong. The same output for character arrays will be if you will not use std::ios::binary. Try for example the following


const char *theEmployeeID = "AD125";
const char *theEmployeeName = "CHIRSJYE";
const char *theEmployeeDOB = "13-10-1991"

std::cout << theEmployeeID << theEmployeeName << theEmployeeDOB;

You will get the same result on the console

AD125CHIRSJYE13-10-1991



Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 10.10.12 17:01. Заголовок: i tried the code . y..


i tried the code . ya , same result.

but then my variable actually not char..

it's string , i using string for all my variable. so why i still get the error result instead ?

Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 10.10.12 17:29. Заголовок: Please show a short ..


Please show a short example (the shorter the example the better) where you get the error result? And what is the error result?

Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 10.10.12 18:30. Заголовок: just a part of my co..


just a part of my code

outFile.open( "employee.txt" , ios:: out || ios :: binary );
size++;
outFile << size << "\n" ;

for( int i = 0 ; i < size ; i++ ){
outFile << theEmployee.EmployeeID << endl << theEmployee.EmployeeName << endl
<< theEmployee.EmployeeDepartment << endl
<< theEmployee.EmployeeDOB << endl << theEmployee.EmployeeAddress
<< endl << theEmployee.EmployeeWorkHours << endl << theEmployee.PayRate
<< endl << theEmployee.totalSalary << endl;
}

outFile.close();

if i do like dis . all my txt data will be stick together . it wont endl after a detail was save it .
so get it?

but if i remove the ios :: binary
everything work fine

Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 10.10.12 18:43. Заголовок: The data are the sam..


The data are the same except that in the text mode numbers are written as sequence of characters while in the binary mode numbers are written according their internal representations.
In the text mode all you data are also stick together. Only when a file is outputed on screen in the text mode new line character has special interpretationthat is after a new line character next data are placed in the next screen line.

Спасибо: 0 
ПрофильЦитата Ответить



ссылка на сообщение  Отправлено: 11.10.12 06:46. Заголовок: so how should i prev..


so how should i prevent the problem occur??

Спасибо: 0 
ПрофильЦитата Ответить
Ответ:
1 2 3 4 5 6 7 8 9
большой шрифт малый шрифт надстрочный подстрочный заголовок большой заголовок видео с youtube.com картинка из интернета картинка с компьютера ссылка файл с компьютера русская клавиатура транслитератор  цитата  кавычки моноширинный шрифт моноширинный шрифт горизонтальная линия отступ точка LI бегущая строка оффтопик свернутый текст

показывать это сообщение только модераторам
не делать ссылки активными
Имя, пароль:      зарегистрироваться    
Тему читают:
- участник сейчас на форуме
- участник вне форума
Все даты в формате GMT  3 час. Хитов сегодня: 43
Права: смайлы да, картинки да, шрифты да, голосования нет
аватары да, автозамена ссылок вкл, премодерация откл, правка нет