Example:
std::ifstream in("some_file.txt");
std::string line; // must be outside ?
while(getline(in,line)){
// how to make 'line' only available inside of 'while' ?
}
Do-while loops won't work for the first iteration:
std::ifstream in("some_fule.txt");
do{
std::string line;
// line will be empty on first iteration
}while(getline(in,line));
Of course one can always have a if(line.empty()) getline(...) but that doesn't really feel right.
I also thought of abusing the comma operator:
while(string line, getline(in,line)){
}
but that won't work, and MSVC tells me that's because line isn't convertible to bool. Normally, the following sequence
statement-1, statement-2, statement-3
should be of type type-of statement-3 (not taking overloaded operator, into account). I don't understand why that one doesn't work. Any ideas?
You could cheat a little bit and just make a superfluous block:
{
std::string line;
while (getline(in, line)) {
}
}
This isn't technically "the same scope", but as long as there's nothing else in the outer block, it's equivalent.
A for loop will work, I do this all the time:
for (std::string line;
getline(in,line); )
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With