I have numerical text data lines ranging between 1mb – 150 mb in size, i need to write lines of numbers related to heights, for example: heights=4 , new text must include lines: 1,5,9,13,17,21…. consequentially.
i have been trying to find a way to do this for a while now, tried using a list instead of vector which ended up with compilation errors.
I have cleaned up the code as advised. It now writes all lines sample2 text, all done here. Thank you all
I am open to method change as long as it delivers what i need, Thank you for you time and help.
following is what i have so far:
#include <iostream>
#include <fstream>
#include <string>
#include <list>
#include <vector>
using namespace std;
int h,n,m;
int c=1;
int main () {
cout<< "Enter Number Of Heights: ";
cin>>h;
ifstream myfile_in ("C:\\sample.txt");
ofstream myfile_out ("C:\\sample2.txt");
string line;
std::string str;
vector <string> v;
if (myfile_in.is_open()) {
myfile_in >> noskipws;
int i=0;
int j=0;
while (std::getline(myfile_in, line)) {
v.push_back( line );
++n;
if (n-1==i) {
myfile_out<<v[i]<<endl;
i=i+h;
++j;
}
}
cout<<"Number of lines in text file: "<<n<<endl;
}
else cout << "Unable to open file(s) ";
cout<< "Reaching here, Writing one line"<<endl;
system("PAUSE");
return 0;
}
You need to use
seekgto set the position at the beginning of the file, once you have read it (you have read it once, to count the lines (which I don’t think you actually need, as this size is never used, at least in this piece of code)And what is the point if the inner
while? On each loop, you haveSo on each loop,
igets 1, so you output the element with index1all the time. Which is not the first element, as indices start from0. So, once you putseekgor remove the firstwhile, your program will start to crash.So, make
istart from0. And get it out of the twowhileloops, right at the beginning of theif-statement.Ah, the second
whileis also unnecessary. Leave just the first one.EDIT:
Add
before
seekgto clear the flags.Also, your algorithm is wrong. You’ll get seg fault, if h > 1, because you’ll get out of range (of the vector). I’d advise to do it like this: read the file in the
while, that counts the lines. And store each line in the vector. This way you’ll be able to remove the second reading,seekg,clear, etc. Also, as you already store the content of the file into avector, you’ll NOT lose anything. Then just useforloop with steph.Again edit, regarding your edit: no, it has nothing to do with any flags. The
if, where you comparei==jis outside the while. Add it inside. Also, incrementjoutside theif. Or just removejand usen-1instead. Like