C++:如何使用CIN和File两种方式获取输入

C++: how to get input using two kind of ways,like cin and file?

本文关键字:两种 方式 获取 输入 File 何使用 CIN C++      更新时间:2023-10-16

我写了一个可以从文件中获取信息的c ++程序,但它必须支持两种读取数据的方式。

第一种方法是将文件名作为命令行参数传递:./a.out a.txt

第二个是通过从管道读取: cat a.txt | ./a.out

第二种方式对我来说更重要,也更困难。怎么能做到呢?

以下是有关我的问题的详细信息:

有一个类,我定义如下:

类 API_EXPORT SamReader{

// constructor / destructor

公共: 山姆读者(无效); ~三读器(无效);

// closes the current SAM file
bool Close(void);
// returns filename of current SAM file
const std::string GetFilename(void) const;
// return if a SAM file is open for reading
bool IsOpen(void) const;
// opens a SAM file
// *** HERE IS MY QUESTION
bool Open(const std::string& filename);
bool Open(std::istream cin); //HERE~~~~
// retrives next available alignment
bool LoadNextAlignment(BamAlignment& alignment);

私人: 内部::SamReaderPrivate * d;};

我有办法输入文件并获得结果,但我需要在此类中添加一个 func,使其可以从标准输入...

感谢您的帮助,我是这里的新人,我非常感谢刚才帮助我的人。

要从管道读取,您的程序只需要从 stdin读取。 这就是 shell 中的管道的工作方式,如果您运行 a | b,它只是将 a 标准输出上的所有输出传递到 b 的 stdin。

所以基本上你的程序需要涵盖 2 种情况:(1) 从文件中读取(如果提供了文件),(2) 否则从 stdin 读取。

为了避免代码重复,最简单的方法始终是从标准输入中读取。 这显然将涵盖(2)。 要涵盖 (1),当文件作为参数提供时,请使用 freopen 用该文件覆盖 stdin。

#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char** argv) {
  if (argc > 1) {
    freopen(argv[1], "r", stdin);
  }
  string s;
  while (cin >> s) {
    cout << s << endl;
  }
  return 0;
}

演示其工作原理

$ g++ test.cc
$ cat content
This
is
a
test
$ ./a.out content
This
is
a
test
$ cat content | ./a.out
This
is
a
test
就像

@Sander De Dycker说的那样。这不关程序的事。这取决于您使用的外壳,我猜您使用经典的sh。

你可以编写一个非常简单的 c++ 程序,例如:

#include <string>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
    vector<string> v;
    string s;
    while (cin >> s)
    v.push_back(s);
    for (int i = 0; i != v.size(); ++i)
    cout << v[i] << endl;
    return 0;
}

然后,您可以键入 ./a.out a.txt 以将a.txt用作输出,或键入 cat a.txt | ./a.out 以将a.txt用作输入。 或者您也可以混合使用这两个命令。