2011-03-17 73 views
0

编辑:我在代码中有一个愚蠢的错误,并解决了这个问题,所以现在事情是可以解释的。我相应地更新了我的帖子。检查stdin/std :: cin是否支持寻求

以下代码显示在行缓冲区内寻找工作。

首先,结果当管道东西进入程序。

$ 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 == ? 

其次,我输入“a [enter] s [enter] d [enter] f [enter]”。

$ ./seektest 
a 
stdin supports fseek(). 
s 
c == s 
std::cin supports seekg(). 
d 
c == d 
c == 

第三,我打字 “ASDF” 每个getc/get()通话。

$ ./seektest 
asdf 
stdin supports fseek(). 
asdf 
c == a 
std::cin supports seekg(). 
asdf 
c == a 
c == s 

寻求似乎在行缓冲区内工作。

这是代码。

#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"); 
    } 
    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; 
} 

回答

1

看起来像你对我有你的情况在这里逆转:

if (std::cin.fail()) { 
    fprintf(stdout, "std::cin supports seekg().\n"); 
} else { 
    fprintf(stdout, "std::cin does not support seekg().\n"); 
} 

std::cin “支持seekg()” 如果失败

+0

哎呀,你是对的。抱歉。 – Manuel 2011-03-17 08:39:21