reading ifstream

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.

1
2
3
4
5
6
7
8
9
int openAndReadNums(string filename, ifstream& fn, double&num1,double &num2)
 {

                  fn.open(filename.c_str());
                  while(fn.good())
                  {
                        fn>>num1;
                        fn>>num2;
                  }
Line 4 try while (!fn.eof())

Your file is still "good" even if it has reached the end of the data. It goes "bad" only after you've tried to read past the end of the file.
1
2
3
4
while ( fn >> num1 >> num2 )
{
//...
}


Also, you shouldn't need .c_str() with a decent compiler.
Hello clayoda,

Given your code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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. 


I think this should work for you, but untested:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// <--- 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!";

		return true;
	}

	while (fn >> num1 >> num2)  // <--- Reads file until the "eof" bit is set.
	{
		// <--- Code to process numbers read.
	}

	// <--- Anything needed after while loop.

	return false;
}


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.

Andy

Edit: tag.
Last edited on
Topic archived. No new replies allowed.