tech-pkg archive
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]
Re: wip/mu: std::getline returning falsy value
On Thu, Apr 18, 2024 at 01:24:39PM +0000, Kevin Bloom wrote:
> > This would happen e.g. if the stdin of the program has been closed.
>
> Do you have any ideas of what would cause such a thing to happen? I'm
> assuming it shouldn't happening since it's in the standard library...
No, I mean it would probably happen outside of the standard library.
Below is an example that demonstrates it, it's output looks like:
--8<--
> ./a.out
hi there
the line you entered: hi there
something bad happened to std::cin!
-->8--
So the first std::getline() call works fine, but then the fclose(stdin)
makes the second call fail.
Martin
#include <string>
#include <iostream>
int main(int argc, char **argv)
{
std::string aLine;
std::getline(std::cin, aLine);
std::cout << "the line you entered: " << aLine << std::endl;
fclose(stdin);
std::getline(std::cin, aLine);
if (!std::cin) {
std::cout << "something bad happened to std::cin!" << std::endl;
return 1;
}
std::cout << "the line you entered: " << aLine << std::endl;
return 0;
}
Home |
Main Index |
Thread Index |
Old Index