ofBufferFromFile, how to read lines with an iterator?

I’m updating code from 0084 to git master and I can’t use deprecated commands to read lines from a text. isLastLine and getNextLine are deprecated.

how to read txt file lines using an iterator?
Thank you!

you can keep using them even if they are deprecated but the new syntax is:

for(auto line: buffer){
    cout << line.asString() << endl;
}

or whatever you want to do with each line

this syntax is lovely, btw…

actually, if it’s only one line long, will you not get a character iterator? which might not be what you expect…

oh yeah sorry that actually returns a character iterator, the correct syntax is:

for(auto line: buffer.getLines()){
    cout << line.asString() << endl;
}

which an also be:

for(auto line: buffer.getLines()){
    for(auto c: line){
        cout << line.asString() << endl;
   }
}

to iterate on every character on every line

Hey @arturo thanks for the quick answer.
It is not running here in Git Master, it doesn’t recognize “asString()” function

No member named 'asString' in 'std::basic_string<char>'
	ofBuffer buff2 = ofBufferFromFile("sliders/_guis.txt");
    for(auto line: buff2.getLines()){
        cout << line.asString() << endl;
    }

agh, yeah : ) you don’t need the asString, this way of using the iterator will already dereference it, so what you get is already a string not the line object. you just need to do

    ofBuffer buff2 = ofBufferFromFile("sliders/_guis.txt");
    for(auto line: buff2.getLines()){
        cout << line << endl;
    }

you can also do

    ofBuffer buff2 = ofBufferFromFile("sliders/_guis.txt");
    for(auto & line: buff2.getLines()){
        cout << line << endl;
    }

to avoid copying the string of each line (note the & in the for loop) bu in this case it would be negligible in terms of any performance gain and you can’t modify the original like that

1 Like

Thanks @arturo. I had to update functions for iterator because old code is not only deprecated but not running on git master. It is no problem since now I can diferentiate both using ofGetVersionInfo.