Having trouble opening a text file

Hello! Good morning!

I'm trying to do some math with a text file that looks like:

Mary Baggins 30000 20000 0.10
Tom Clark 20000 2000 0.08
Mark Twain 25000 10000 0.05
Rebecca Brown 10000 100 0.02

, where each column is clearly char, int, int and float.
I declared the above variables in class as public variables.
Using the while loop, I want to read the data correctly line by line and 'cout' the entire data.
Also, I want to use loop statement to perform operations with the int and float variables.

The following is my code:


#include <iostream>
#include <fstream>
using namespace std;

class myclass{

public:

char A[20];
int B;
int C;
float D;

float Total;

float addition (int secondcolumn, int third, float fourth)
{ float sum = secondcolumn + third + fourth;
return sum; }

};

int main()

ifstream textfile;
textfile.open("textfile.txt", ios::in);

myclass data;

if(textfile.is_open())

{

while (textfile >> data.A >> data.B >> data.C >> data.D)
{
cout << data.A <<" " << data.B << " "<<data.C <<" " <<data.D << endl;
} // I thought this part would print the data out, but it didn't work..


textfile.close(); }

return 0; }




================


The code compiles, but shows nothing once I execute it.
In addition, I added an else statement to check if the file was open correctly.
The else statement does not appear, so my text file was read correctly.
I am expecting it to show the data I input.

Also, I would like to do some math with the numerical data line by line, but cannot find a way to write the code.

I appreciate your help in advance!

textfile >> data.A reads Mary. >> data.B tries to read Baggins into int but fails. So body of loop is not executed.

If you have two words, you need to read them both.
Topic archived. No new replies allowed.