Can reading a character from the std::istream result in failbit being set?

Can reading a character from the std::istream result in failbit being set?

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>

int main()

    for(std::string str; std::getline(std::cin, str);)
    {
        //....
    }

    return 0;
}


Can this loop ever be terminated by the fact that failbit alone is being set (not eofbit and failbit together)?
try compiling your 'program' and check the error messages
1
2
3
4
5
6
7
8
9
int main(){

    for(std::string str; std::getline(std::cin, str);)
    {
        //....
    }

    return 0;
}


That was not the important part anyway. Just want to know if reading into a single char can ever set a failbit unless EOF is reached :

1
2
char ch;
std::cin >> ch;
Last edited on
> Can this loop ever be terminated by the fact that failbit alone is being set (not eofbit and failbit together)?

In theory, only if str.max_size() characters have been extracted into the string and the next character in the input buffer is not '\n'

In practice, we can safely ignore this possibility; str.max_size() would be too huge.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>

int main()
{
    std::cout << std::string{}.max_size() << '\n' ;

    for(std::string str; std::getline(std::cin, str);)
    {
        //....
    }

    return 0;
}

http://coliru.stacked-crooked.com/a/9087c8dec0625f40
http://rextester.com/KMVUU53507


> Just want to know if reading into a single char can ever set a failbit unless EOF is reached :

No; if the failbit is set, the eofbit will also be set.
Last edited on
Thank you very much man, much appreciated! :)
Last edited on
Topic archived. No new replies allowed.