EDIT: I had a stupid bug in the code and fixed this, so things are explicable now. I updated my post accordingly.
The following code shows that seeking within the line buffer works.
First, the result when piping something into the program.
$ echo 'asdf' | ./seektest
stdin does not support fseek()
c == s
std::cin does not support seekg()
Second read to std::cin failed!
c == ?
Second read to std::cin failed!
c == ?
Second, I typed "a[enter]s[enter]d[enter]f[enter]".
$ ./seektest
a
stdin supports fseek().
s
c == s
std::cin supports seekg().
d
c == d
c ==
Third, I typed "asdf" for each getc
/get()
call.
$ ./seektest
asdf
stdin supports fseek().
asdf
c == a
std::cin supports seekg().
asdf
c == a
c == s
Seeking appears to work within the line buffer.
Here is the code.
#include <iostream>
#include <cstdio>
int main(int argc, char ** argv)
{
// Try cstdio.
int x = fgetc(stdin);
if (x < 0) {
fprintf(stderr, "First read to stdin failed!.");
}
int res = fseek(stdin, -1, SEEK_CUR);
if (!res) {
fprintf(stdout, "stdin supports fseek().\n");
} else {
fprintf(stdout, "stdin does not support fseek()\n");
}
x = fgetc(stdin);
if (x < 0) {
fprintf(stderr, "Second read to stdin failed!\n");
}
char c = x;
fprintf(stdout, "c == %c\n", c);
// Try iostream.
x = std::cin.get();
if (std::cin.fail()) {
fprintf(stderr, "First read to std::cin failed!\n");
}
开发者_C百科 std::cin.seekg(-1, std::ios::cur);
if (std::cin.fail()) {
fprintf(stdout, "std::cin does not support seekg()\n");
} else {
fprintf(stdout, "std::cin supports seekg().\n");
}
c = std::cin.get();
if (std::cin.fail()) {
fprintf(stderr, "Second read to std::cin failed!\n");
}
fprintf(stdout, "c == %c\n", c);
c = std::cin.get();
if (std::cin.fail()) {
fprintf(stderr, "Second read to std::cin failed!\n");
}
fprintf(stdout, "c == %c\n", c);
return 0;
}
Looks to me like you have your condition reversed here:
if (std::cin.fail()) {
fprintf(stdout, "std::cin supports seekg().\n");
} else {
fprintf(stdout, "std::cin does not support seekg().\n");
}
std::cin
"supports seekg()
" if it failed?
精彩评论