How to read line by line
I'm just starting in C ++, so please don't judge me. This is probably a stupid question, but I want to know.
I have a text file like this (there will always be 4 numbers, but the number of lines 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 this is what I want to do: I want to read this file line by line and put each number in a variable. Then I will do some functions with those 4 numbers and then I want to read the next line and execute some functions again with those 4 numbers. How can i do this? This is how much 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 this is how I read the whole file into an array, but I want to read it line by line, execute my function, and then read the next line.
+3
source to share
1 answer
For reading data from a file, I find a stream of strings is really useful.
How about 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;
}
+2
source to share