carmelo wrote:
Hi! I need to read and store data from a file, but I don't the name of
it; Is this code correct and is there a better way to do this thing??
Define "better".
It sounds like the filename is unknown at compile time, but known at run
time. There are a few ways you could get the name, a few include:
1. Accept filename as run time paramater. I.e.
myprog filename.ext
2. Accept the filename as user input
3. Accept the file through std::cin using OS piping.
4. Accept the filename through some other method (graphical input, stored in
a file, etc..)
It depends on what you mean by "better".
int main()
{
cout << " type file name:"
char * name;
cin >name;
This is an error. name is an uninitialied pointer to a character. Yet you
never allocated any memmory for it, so it points .. somewhere. Anywhere.
But not to anything valid. Most likely when the program hits the cin >>
name a run time error will occur as cin attempts to write to memory your
program doesn't "own". Better is:
std::string name;
std::getline( std::cin, name );
getline is better than >in this case because getline will allow a space,
>will stop when it hits the first space leaving the remainder in the
buffer.
ifstream indata;
Might as well just open it here.
std::ifstream indata( name );
int num1; // variables for input values
int num2;
int num3;
indata.open(name); // opens the file
So that line isn't needed anymore.
if(!indata) { // file couldn't be opened
cerr << "Error: file could not be opened" << endl;
exit(1);
}
indata >num1;
indata >num2;
indata >num3;
}
You are not checking if the data is valid. Better is:
if ( ! indata >num1 >num2 >num3 )
{
std::cerr << "File dataformat error." << std:;endl;
exit( 1 );
}
// Data is good, proceed
}
--
Jim Langston
ta*******@rocketmail.com