【问题标题】:Check whether stdin/std::cin support seeking检查 stdin/std::cin 是否支持查找
【发布时间】:2011-03-17 08:20:53
【问题描述】:

编辑:我在代码中有一个愚蠢的错误并修复了它,所以现在可以解释了。我相应地更新了我的帖子。

以下代码显示在行缓冲区内查找是有效的。

首先,将某些内容导入程序时的结果。

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

第三,我为每个getc/get() 呼叫输入“asdf”。

$ ./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;
}

【问题讨论】:

    标签: c++ io terminal fifo seek


    【解决方案1】:

    在我看来,你的情况在这里颠倒了:

    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()" 如果它失败

    【讨论】:

      猜你喜欢
      • 2015-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-26
      • 2011-10-17
      • 2011-10-26
      • 2021-10-26
      相关资源
      最近更新 更多