Reputation: 61
I've been working on a C++ program where I read a files contents and copy then onto another file but it always seem to skip the first line. I've seen others having trouble with this and they used these lines of code:
file.clear();
file.seekg(0);
to reset the position but its not working for me. I've tried it in multiple spots but still no luck. Any ideas? Heres my code.
ofstream write("Mar 23 2013.txt");
for(int x = 1; x <= 50; x++){
stringstream ss;
ss << "MAR23_" << x;
ifstream file(ss.str().c_str());
if(!file.is_open())
cout << ss.str() << " could not be opened/found." << endl;
else{
while(getline(file,line)){
file >> time >> ch >> sensor1 >> ch >> temp >> ch >>
sensor2 >> ch >> sensor3;
file.ignore(numeric_limits<streamsize>::max(), '\n');
//output = convertEpoch(time);
write << time << " Temperature:" << temp << "ºF S1:" <<
sensor1 << " S2:" << sensor2 << " S3:" <<
sensor3 << endl;
}
file.close();
}
}
write.close();
return 0;
Upvotes: 1
Views: 15302
Reputation: 76458
You can read from a text file in basically two ways. Line by line, with getline
, or item by item with >>
. getline
reads a line of text into its argument; after the call to getline
in your code, line
has the text that was read in. Having done that, the extractors in file >> time >> ch ...
read from the spot where getline
left off.
Upvotes: 2
Reputation:
You are missing the first line because you read it in to line
. In fact you should be missing more than just the first line.
Once you read from the file use a string stream.
while (std::getline(infile, line))
{
std::istringstream iss(line);
iss>> time >> ch >> sensor1 >> ch >> temp >> ch >>
sensor2 >> ch >> sensor3;
// ...
}
Upvotes: 9