Reputation: 77
i am just a beginer in c++ so please do not judge me hard. Probably this is silly question but i want to know.
i have a text file like this(there always will be 4 numbers, but the count of rows will vary):
5 7 11 13
11 11 23 18
12 13 36 27
14 15 35 38
22 14 40 25
23 11 56 50
22 20 22 30
16 18 33 30
18 19 22 30
And here is what i want to do: i want to read this file line by line and put each number into variable. Then i will do some functions with this 4 numbers and then i want to read the next line and again do some functions with this 4 numbers. How can i do that? This is as far as i am
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int array_size = 200;
char * array = new char[array_size];
int position = 0;
ifstream fin("test.txt");
if (fin.is_open())
{
while (!fin.eof() && position < array_size)
{
fin.get(array[position]);
position++;
}
array[position - 1] = '\0';
for (int i = 0; array[i] != '\0'; i++)
{
cout << array[i];
}
}
else
{
cout << "File could not be opened." << endl;
}
return 0;
}
but like this i am reading whole file into array, but i want to read it line by line, do my function and then read the next line.
Upvotes: 4
Views: 1151
Reputation: 124
For reading data from file I find the stringstream really helpful.
What about something like this?
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
int main()
{
ifstream fin("data.txt");
string line;
if ( fin.is_open()) {
while ( getline (fin,line) ) {
stringstream S;
S<<line; //store the line just read into the string stream
vector<int> thisLine(4,0); //to save the numbers
for ( int c(0); c<4; c++ ) {
//use the string stream as a new input to put the data into a vector of int
S>>thisLine[c];
}
// do something with these numbers
for ( int c(0); c<4; c++ ) {
cout<<thisLine[c]<<endl;
}
}
}
else
{
cout << "File could not be opened." << endl;
}
return 0;
}
Upvotes: 2