hey guys for an assignment I have to write the function to numbers from a file. The function was already predefined by my professor with the parameters we need. When i use an example file to test it my code is outputting CRAZY numbers that are not in the file.. I was wondering if someone could let me know what I am doing wrong. Ill include the sample function below.
int openAndReadNums(string filename, ifstream& fn, double&num1, double &num2) // <--- Be consistent with its use.
{
fn.open(filename.c_str()); // <--- The ".c_str()" is not needed from C++11 on.
// <--- How do you know that the file is open?
while (fn.good()) // <--- Endless loop until the stream is closed.
{
fn >> num1;
fn >> num2;
}
// <--- Is there something missing here"?
// <--- What should the return value be?
} // <--- This was missing leading me to believe there is something missing after the while loop.
// <--- Calling function. Guessing that it is called from "main" .
if (openAndReadNums(filename, fn,num1, num2))
Return 1;
int openAndReadNums(string filename, ifstream& fn, double &num1, double &num2) // <--- Can you make the return value a "bool"?
{
fn.open(filename);
if (!fn)
{
std::cout << "\n File \"" << filename << "\" did not open!";
returntrue;
}
while (fn >> num1 >> num2) // <--- Reads file until the "eof" bit is set.
{
// <--- Code to process numbers read.
}
// <--- Anything needed after while loop.
returnfalse;
}
The C++ 2011 standards no longer require the use of ".c_str()" when opening a file. A "std::string" will work. Since you did not mention what IDE/Compiler you are using I do not know if a setting in the IDE can be changed or if you need a newer version of the IDE.
Just a note: since you are reading a file it helps to include the file, or a good sample, so everyone can see what you are working with and if you are reading the file correctly.