reading a .txt file

hello, i just started learning to program and i need some help. I've tried searching but i dont understand any of the answers.

so im given a .txt file that looks like this

1 -3.3 5.2
3 5.3 -9.3 5.2 -2.3
4 -0.3 -3.4 4.3 9.3

and it goes on for a while. I'm asked to make c++ read the file and then for each row make it multiply the first number by 11 and add that to the absolute value of the rest of the numbers times 1.9. for example the first row would be [(1*11) + ((3.3+5.2)*1.9)]=27.15 and display the answer on the screen.

i can get c++ to read the file; but i dont get how to assign each number in a row a variable (if thats even possible).the rest should be easy. anyways, if someone could help me with a dumbed down answer that would really help. thanks.
You can use the >> opperator:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <fstream>

std::ifstream ifs("input.txt");

int i;
float f;

ifs >> i; // read an integer like this

ifs >> f; // read a float like this
Welcome to the forum.

You will probably want to use... a vector.

A vector is essentially a beefed up array. You can change its size on the fly, delete stuff and have it shrink, all sorts of things. Here's a few code snippets that will help.

std::vector<double> foo; //Initialize vector

double temp;

cin >> temp;

foo.push_back(temp); //Append to vector

foo.at(i); //Access element of vector

1
2
3
while (!myvector.empty())
    myvector.pop_back();
//Erase the whole vector 


Got an idea of what to do and why I recommend a vector?

-Albatross
Last edited on
Thank you all for the quick replies!!

It took me a while but I got it

thanks!
Topic archived. No new replies allowed.