C++:如何使用CIN和File两种方式获取输入
C++: how to get input using two kind of ways,like cin and file?
我写了一个可以从文件中获取信息的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
用作输入。 或者您也可以混合使用这两个命令。
- 在C++中将函数压缩为两种方式
- 为什么两种不同的对象初始化方式给出不同的输出
- C++:这两种将数字写入矩阵的方式之间是否存在显着的速度差异?
- 将函数作为参数传递的两种方式之间的区别
- 初始化结构的两种方式
- 在两种情况下,铸造的工作方式不同
- 这两种方式有什么区别吗?
- 由于您可以在C 中以两种方式声明复制构造函数,这是正确的方式
- 定义构造函数的两种不同方式
- 尝试在Qt中连接隐藏信号的两种方式之间做出决定
- C++:如何使用CIN和File两种方式获取输入
- 在C++中定义虚拟继承的两种不同方式
- 为什么这两种访问C++映射对部分的方式不同
- openssl sha256两种计算方式的差异
- 在C++OpenMP中使用蒙特卡罗方法以两种方式计算圆周率
- 在堆栈上声明对象的两种方式之间的差异
- 使用默认构造函数的两种方式的区别
- 声明类实例的两种方式的不同之处
- 用两种不同的方式初始化指针会得到两种结果
- 在这两种包含相同标头的方式之间,编译器中是否发生了不同的事情