read/write file contents

B

blip

Is this acceptable ? It seems too easy and too simple...

#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>

struct Person{
char name[25] ;
int age ;
char ssn[9] ;
} person[5] ;



int main(int argc, char *argv[])
{
std::ifstream input ;
std::eek:fstream output ;
std::string name ;
int age ;

input.open("file.txt", std::ios::in) ;
output.open("fileout.txt", std::ios::eek:ut) ;

if(!input){
std::cout << "File not found" << std::endl ;
exit(1) ;
}

for(int i = 0; i < 5; i++)
input >> person.name >> person.age >> person.ssn ;

for(int k = 0; k < 5; k++)
std::cout << person[k].name << " " << person[k].age << " " <<
person[k].ssn << std::endl ;

// write some text to a file
name = "Me" ;
age = 105 ;

output << name << " " << age << std::endl ;





return 0 ;
}


Here's the file contents exactly as in file.txt

bob
44
123-23-4532
fred
61
434-98-7654
hilbert
23
772-81-7108
peter
12
132-64-0132
jake
51
565-61-0909


I'd like to know what you people think of this .

Regards,
Me
 
J

John Ratliff

blip said:
Is this acceptable ? It seems too easy and too simple...

... snip ...


Here's the file contents exactly as in file.txt

bob
44
123-23-4532
fred
61
434-98-7654
hilbert
23
772-81-7108
peter
12
132-64-0132
jake
51
565-61-0909


I'd like to know what you people think of this .

Regards,
Me


It looks okay to me. But I didn't test it. If it works when you run it,
then I'd say it's probably good. Maybe someone sees something wrong I
don't. I only glanced for a minute.

--John Ratliff
 
R

Richard Herring

John Ratliff said:
It looks okay to me. But I didn't test it. If it works when you run it,
then I'd say it's probably good. Maybe someone sees something wrong I
don't. I only glanced for a minute.

As an example of file reading and writing it's OK up to a point, but it
won't work if any of the strings contain spaces. operator>>(istream&,
string&) stops when it reaches whitespace.

For robust code it's probably better to define overloaded operators >>
and << for Person, which validate the data and provide some kind of
quoting convention to deal with the problem of embedded spaces etc.

(And it really ought to test for errors on all the file operations.)

As an example of good program design it has flaws in other areas, but I
don't think that was the point of the question.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top