Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have the 'string line' in the same scope as the 'getline(in,line)' in a 'while(getline(...))' loop?

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?

like image 647
Xeo Avatar asked Dec 10 '25 10:12

Xeo


2 Answers

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.

like image 62
John Flatness Avatar answered Dec 12 '25 00:12

John Flatness


A for loop will work, I do this all the time:

for (std::string line;
     getline(in,line); )
{
}
like image 39
Benjamin Lindley Avatar answered Dec 11 '25 23:12

Benjamin Lindley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!