Hi,

So i have written my code to solve the quadratic equation and it works. The thing I need to do is to read values for 3 variables from an input .txt file until the end of the file and output the answers for each set of variables. The variables are a, b, and c. The values in the file are three per line seperated by spaces. Example below.

a	b	c
1	3	2
1	6	9
3	-2	-1

1	-1	0
1	0	-4
2	2	-2

I am just not sure how to actually go about reading these in line by line. I know i will have to use a loop since the same variables are used over and over again in the function.

Would something like this work? (no formula in yet)

ifstream in_stream;
	ofstream out_stream;

	 in_stream.open(“infile.dat”);
	 out_stream.open(“outfile.dat”);

	int a, b, c;	
	in_stream >> a>> b>> c;		
	out_stream << "the three values for this quadratic are”
		          << a<<b<<c << endl;	
//then i would use them in my function loop

	in_stream.close();
	out_stream.close();

The simplest way if your thinking about using loops, is using arrays to store the values; something like this:

#include <fstream>          // Header File for File Reading
#include <iostream>         // Header File for General I/O-put

using namespace std;        // Use namespacing

float x[10], y[10], z[10];  // floats for loaded values

bool LoadData()           // Function for loading the string
    {
    ifstream in ("InputData.dat");  // Start Loading data from b.dat
    if (in.good())          // If the file is loadable (existing)
       {
       for (int a=0; a<10; a++)
           {
           in >> x[a] >> y[a] >> z[a];
           }
       in.close();             // Stop Loading data form String.dat  
       return true;
       }
    else                    // If the file is unloadable (nonexisting)
       {
       in.close();          // Stop Loading data form String.dat   
       cout << "Could not load the file!" << endl;    // Post error message
       cin.get();           // Pause, to make the user able to read the error message
       return false;        // Exit the program
       } 
    }

int main()
    { 
    if (!LoadData()){return 0;}     // If the function returned 
    // CHECK OUTPUT FUNCTION
    for (int a=0; a<10; a++)
        {
        cout << "x = " << x[a] << " y = " << y[a] << " z = " << z[a] << endl;
        }
    // Calculate function
    // Output function
    cin.get();              // Pause, to make the user able to read the error message
    return 0;               // Exit the program   
    }

EDIT: This code will load 10 x,y and z values, no matter if their even available, so maybe you'll need a little piece of code, to sort out when the file is fully read.
About your calculation loop, simply add it inside a for loop, like the loading one, and make your variables dependend on the "a" value ect.

Hi,

So i have written my code to solve the quadratic equation and it works. The thing I need to do is to read values for 3 variables from an input .txt file until the end of the file and output the answers for each set of variables. The variables are a, b, and c. The values in the file are three per line seperated by spaces. Example below.

a	b	c
1	3	2
1	6	9
3	-2	-1

1	-1	0
1	0	-4
2	2	-2

I am just not sure how to actually go about reading these in line by line. I know i will have to use a loop since the same variables are used over and over again in the function.

Would something like this work? (no formula in yet)

ifstream in_stream;
	ofstream out_stream;

	 in_stream.open(“infile.dat”);
	 out_stream.open(“outfile.dat”);

	int a, b, c;	
	in_stream >> a>> b>> c;		
	out_stream << "the three values for this quadratic are”
		          << a<<b<<c << endl;	
//then i would use them in my function loop

	in_stream.close();
	out_stream.close();

As long as you know that the file is formatted in rows of 3 values, that's the right idea. Just make sure you use a loop to cycle through the lines to the end of file and that the loop includes both your input statements and your function evaluation / calculations.

Thanks Skeen, but the problem with that is that I dont know how many lines the file will contain, therefore the arrays could potentially be filled and still have data left that I am supposed to solve. Is there an easy way to read a line from the input file, place it into the variables, run my code, and do it over and over until i hit the end of the file?

The simplest way if your thinking about using loops, is using arrays to store the values; something like this:

#include <fstream>          // Header File for File Reading
#include <iostream>         // Header File for General I/O-put

using namespace std;        // Use namespacing

float x[10], y[10], z[10];  // floats for loaded values

bool LoadData()           // Function for loading the string
    {
    ifstream in ("InputData.dat");  // Start Loading data from b.dat
    if (in.good())          // If the file is loadable (existing)
       {
       for (int a=0; a<10; a++)
           {
           in >> x[a] >> y[a] >> z[a];
           }
       in.close();             // Stop Loading data form String.dat  
       return true;
       }
    else                    // If the file is unloadable (nonexisting)
       {
       in.close();          // Stop Loading data form String.dat   
       cout << "Could not load the file!" << endl;    // Post error message
       cin.get();           // Pause, to make the user able to read the error message
       return false;        // Exit the program
       } 
    }

int main()
    { 
    if (!LoadData()){return 0;}     // If the function returned 
    // CHECK OUTPUT FUNCTION
    for (int a=0; a<10; a++)
        {
        cout << "x = " << x[a] << " y = " << y[a] << " z = " << z[a] << endl;
        }
    // Calculate function
    // Output function
    cin.get();              // Pause, to make the user able to read the error message
    return 0;               // Exit the program   
    }

Thanks Skeen, but the problem with that is that I dont know how many lines the file will contain, therefore the arrays could potentially be filled and still have data left that I am supposed to solve. Is there an easy way to read a line from the input file, place it into the variables, run my code, and do it over and over until i hit the end of the file?

Use an input check

if (in >> a >> b >> c) {
    //...perform calculation...
} else {
    //...report EOF or other error...
}

As long as you can pull values into the variables, the conditional will return true and perform the calculation(s). If you reach EOF, the condition will return false and bypass the calculation.

You can either use a similar statement for controlling your loop (which would preclude the use of the if statement, and still require you to verify that you aren't going to overflow your array(s)) or add a break statement to the else block.

@ Fbody, so i dont need to tell it when its reached the end of the file? just tell it to keep running while it reads numbers?

As long as you know that the file is formatted in rows of 3 values, that's the right idea. Just make sure you use a loop to cycle through the lines to the end of file and that the loop includes both your input statements and your function evaluation / calculations.

@Fbody, haha i dont know how but you are answering my questions right before i finish posting them. Thanks a bunch.

Will that output an error? i would like to avoid that.

@ Fbody, so i dont need to tell it when its reached the end of the file? just tell it to keep running while it reads numbers?

@ Fbody, so i dont need to tell it when its reached the end of the file? just tell it to keep running while it reads numbers?

Correct.

The loop design is known as an "Indeterminate Loop". Indeterminate loops allow you to run indefinitely until you detect a condition that requires them to stop. In this case, that condition is no more available input from the file.

Thanks Skeen, but the problem with that is that I dont know how many lines the file will contain, therefore the arrays could potentially be filled and still have data left that I am supposed to solve. Is there an easy way to read a line from the input file, place it into the variables, run my code, and do it over and over until i hit the end of the file?

I would use vectors (dynamic arrays) instead of arrays, and simply expand the vector for each input. So you'll start of with a vector with the size of 1, and when you're loading the input, you'll expand it with 1 (that way you're able to load as many variables as you need), and when you're filling the vector with zeroes in both x,y,z then break the loop. However then you'll have to make sure, that none of the functions are using x=0,y=0,z=0 as coefficients.

Another way would be simply to make a piece of code to check to total number of lines in the file, and then make an array with fits that.

Btw, let me get this straight, you're interested in doing this:

//Load var x,y,z
//Calculate
//Save result
//Redo
//Exit when all is done

instead of:

//Load all vars
//Do all calculations
//Save all results
//Exit program

Because, if you're going for the first one, then I'll write a new example, and using the first one, you'll only need like 1 var for each x,y,z instead of the array.

yep the first way is the way i want to do it. i am not familiar with dynamic arrays yet (somthing i am clearly going to have to look into)

could you provide a simple example of a vector?

I would use vectors (dynamic arrays) instead of arrays, and simply expand the vector for each input. So you'll start of with a vector with the size of 1, and when you're loading the input, you'll expand it with 1 (that way you're able to load as many variables as you need), and when you're filling the vector with zeroes in both x,y,z then break the loop. However then you'll have to make sure, that none of the functions are using x=0,y=0,z=0 as coefficients.

Another way would be simply to make a piece of code to check to total number of lines in the file, and then make an array with fits that.

Btw, let me get this straight, you're interested in doing this:

//Load var x,y,z
//Calculate
//Save result
//Redo
//Exit when all is done

instead of:

//Load all vars
//Do all calculations
//Save all results
//Exit program

Because, if you're going for the first one, then I'll write a new example, and using the first one, you'll only need like 1 var for each x,y,z instead of the array.

yep the first way is the way i want to do it. i am not familiar with dynamic arrays yet (somthing i am clearly going to have to look into)

could you provide a simple example of a vector?

About the first way, then simply use this, this will the entire file, and stop when it's loaded the last line:

#include <fstream>          // Header File for File Reading
#include <iostream>         // Header File for General I/O-put

using namespace std;        // Use namespacing

int main()
    {
    double x,y,z;
    double Lastx, Lasty, Lastz;
    ifstream in ("InputData.dat");
    while (1)
          {
          in >> x >> y >> z;
          if (x==Lastx && y==Lasty && z==Lastz){break;}
          // Calculate and output
          Lastx=x; Lasty=y; Lastz=z;                   
          }
    cin.get();              // Pause, to make the user able to read the error message
    return 0;               // Exit the program   
    }

Simply add your output and calculation, and it should work :)

Sweet thanks. This looks great. Ill post my final code here if you were interested in seeing it.

About the first way, then simply use this, this will the entire file, and stop when it's loaded the last line:

#include <fstream>          // Header File for File Reading
#include <iostream>         // Header File for General I/O-put

using namespace std;        // Use namespacing

int main()
    {
    double x,y,z;
    double Lastx, Lasty, Lastz;
    ifstream in ("InputData.dat");
    while (1)
          {
          in >> x >> y >> z;
          if (x==Lastx && y==Lasty && z==Lastz){break;}
          // Calculate and output
          Lastx=x; Lasty=y; Lastz=z;                   
          }
    cin.get();              // Pause, to make the user able to read the error message
    return 0;               // Exit the program   
    }

Simply add your output and calculation, and it should work :)

yep the first way is the way i want to do it. i am not familiar with dynamic arrays yet (somthing i am clearly going to have to look into)

could you provide a simple example of a vector?

Writing to a vector and loading from it, example:

// vector::push_back
#include <iostream>
#include <vector>
using namespace std;

int main ()
{
  vector<int> myvector; // Inti the vector
  int myint=0;          // Inti the var

while (1)
  {
  myvector.push_back (myint);
  myint++;
  if (myint==10){break;}
  }
  
  for (int a=0; a < myint; a++)
  cout << "Vector spot: " << a << " stores " << myvector[a] << endl;
  
  system("PAUSE");
  return 0;
}

Sweet thanks. This looks great. Ill post my final code here if you were interested in seeing it.

Sure thing :) - Lemme see it when you're done

As long as you're posting examples here's how it would work the way I mentioned:

iint main() {
	double a=0.0, b=0.0, c=0.0;
	double root1 = 0.0, root2 = 0.0;
	bool hasRealRoots = true;
	ifstream inFile("coefficients.dat");
	ofstream outFile("roots.txt");
	
	while(inFile >> a >> b >> c) {
		/* check for real roots */
		if (hasRealRoots) {
			/* perform your calculations */
			outFile << root1 << " " << root2 << endl;
		} else {
			outFile << "n/a" << " " << "n/a" << endl;
		}
	}

	cout << "All data has been processed." << endl;

	return 0;
}

As long as you're posting examples here's how it would work the way I mentioned:

Remember that it's possible that the function only has 1 root, and not 2, in rare cases, you should check for that with the determinant, and use an "if" statement to write out only that one root, if that's the case.

Remember that it's possible that the function only has 1 root, and not 2, in rare cases, you should check for that with the determinant, and use an "if" statement to write out only that one root, if that's the case.

Correct, in that case, both roots are identical. Problem is, if you're going to read that information back into the same program or into another program, you need to satisfy both input variables or the result pairings later in the input stream will get fubarred.

Correct, in that case, both roots are identical. Problem is, if you're going to read that information back into the same program or into another program, you need to satisfy both input variables or the result pairings later in the input stream will get fubarred.

True what are you doing if you don't got any results, ect, there are no roots?

True what are you doing if you don't got any results, ect, there are no roots?

I had to do an object-oriented version of a quadratic solver for my C++ class last month, but I just had to output to console, not store in a file.

As far a no roots situation is concerned I didn't dig that far into it for a complete solution to Ponomous' situation. I just put the /* check for real roots */ block and outFile << "n/a" << " " << "n/a" << endl; in there as placeholders for looking at the radicand to determine if the equation is solvable for the particular set of coefficients. The boolean hasRealRoots would be modified with an if - then within that block. Additional design or input validation would be required if hasRealRoots gets modified to false.

I had to do an object-oriented version of a quadratic solver for my C++ class last month, but I just had to output to console, not store in a file.

Really what is the big difference between posting it to the console and saving it to the file, shouldn't be a lot of code you'll need to edit?

Really what is the big difference between posting it to the console and saving it to the file, shouldn't be a lot of code you'll need to edit?

If you're just outputting, there is no difference. Problem is, if you're sending to a file, it's likely to be read back into a program at some point and you have to take that into consideration.

If you're just outputting, there is no difference. Problem is, if you're sending to a file, it's likely to be read back into a program at some point and you have to take that into consideration.

Sure you have to, like if theres just one root, simply make a char instead of an integer as the secondary root, and detect that when you read it into the file at that later point or something, wouldn't that be a simply solution?

Sure you have to, like if theres just one root, simply make a char instead of an integer as the secondary root, and detect that when you read it into the file at that later point or something, wouldn't that be a simply solution?

You could possibly do something with a datatype detection after the fact. The issue is that if you try to read a character or a string into an integer you will corrupt your input stream. Once that happens, you have to reset the stream.

Or, simply use the equality comparison on root1 and root2 and modify your behavior based on the result.

Either way works, it's a matter of preference and specification. I think we've debated it enough. What do you say we let it go?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.