Read only one line using seekg
Hello,
I am just learning how to use the seekg operator. In the code I have written, my intent was to move to the third line of data in an external text file, work with that line of data, and then stop. I used an if statement (if newValue == '\n') to try and tell the program that my wish is to read one, and only one line of code.
I have had success in getting it to read the line I want, but it also reads every line after that line, rather than breaking once the newline character is encountered. Can someone help me tell this program what I really want it to do?
Here is my program:
Code:
/* This program will make a first pass to find the average
* of the numbers in an external file,
* and a second pass to find the difference between
* each number and the average.
* It is being modified to read and operate on
* only one line from the external data file.
*/
#include <iostream>
#include <fstream>
#include <cassert>
using namespace std;
int main()
{
ifstream inStream("data.txt");
assert(inStream.is_open());
double newValue,
sum = 0.0,
average = 0.0;
int count = 0;
for (;;)
{
inStream >> newValue;
if (inStream.eof()) break;
sum += newValue;
count++;
}
if (count > 0)
average = sum / count;
inStream.clear();
inStream.seekg(24, ios::beg);
// 12 bytes per line in data.txt file
for (;;)
{
inStream >> newValue;
if (inStream.eof()) break;
cout << "New Value = " << newValue << ": " << newValue - average << endl;
if (newValue == '\n') break;
}
inStream.close();
}