When I'm trying to read data from a file, it is not updating the value of tempString2.
Instead of grabbing and splitting the new line, it just holds the last value of the first data line.
The reason I believe that the second getline is the issue is that the data is being read in, and the loops are running the exact number of times that I need them to.
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
void PopulateWindLog(int dataIndex, std::string fileName, int const headerVecSize)
{
std::string tempString;
std::string tempString2;
std::stringstream tempStream;
// open data file
std::ifstream dataFile(fileName);
// skip the header line
std::getline(dataFile, tempString);
// while there is still data left in the file
while(std::getline(dataFile, tempString))
{
tempStream << tempString;
std::cout << tempString << std::endl;
for(int i = 0; i < headerVecSize; i)
{
std::getline(tempStream, tempString2, ',');
std::cout << tempString2 << std::endl;
if(i == dataIndex)
{
std::cout << tempString2 << " INSIDE IF STATEMENT !!!! " << std::endl;
}
}
}
}
This is the dataset that I'm using. For replication, I'm looking for column 'S' (index 10). headerVecSize is 18.
WAST,DP,Dta,Dts,EV,QFE,QFF,QNH,RF,RH,S,SR,ST1,ST2,ST3,ST4,Sx,T
31/03/2016 9:00,14.6,175,17,0,1013.4,1016.9,1017,0,68.2,6,512,22.7,24.1,25.5,26.1,8,20.74
31/03/2016 9:10,14.6,194,22,0.1,1013.4,1016.9,1017,0,67.2,5,565,22.7,24.1,25.5,26.1,8,20.97
31/03/2016 9:20,14.8,198,30,0.1,1013.4,1016.9,1017,0,68.2,5,574,22.7,24,25.5,26.1,8,20.92
This is the output that I'm getting. Output of the built program
CodePudding user response:
std::getline()
extracts characters from input and appends them to str until one of the following occurs (checked in the order listed)
- end-of-file condition on input, in which case, getline sets eofbit.
- the next available input character is delim, as tested by Traits::eq(c, delim), in which case the delimiter character is extracted from input, but is not appended to str.
- str.max_size() characters have been stored, in which case getline sets failbit and returns.
(from https://en.cppreference.com/w/cpp/string/basic_string/getline)
So after reading all elements from your first input line, tempstream.good()
is false. No further input is read.
Proposed solution: Move definition of tempstream
into your while
loop. You will get a stream in good
state for each line.