使用istream_iterator并从标准输入或文件中读取 [英] Using istream_iterator and reading from standard input or file
问题描述
我正在用Microsoft Visual C ++编写程序,我希望我的程序可以使用istream_iterator
从标准输入或文件中读取.谷歌搜索互联网还没有显示出我认为必须如此简单.因此,例如,我可以轻松编写此代码并从标准输入中读取内容:
I'm writing in Microsoft Visual C++ and I'd like my program to either read from standard input or a file using the istream_iterator
. Googling the internets hasn't shown how simple I think it must be. So for example, I can write this pretty easily and read from standard input:
#include <iostream>
#include <string>
#include <iterator>
using namespace std;
int main()
{
istream_iterator<string> my_it(cin);
for (; my_it != istream_iterator<string>(); my_it++)
printf("%s\n", (*my_it).c_str());
}
或者我可以编写并读取文件:
Or I can write this and read from a file:
#include <iostream>
#include <string>
#include <iterator>
#include <fstream>
using namespace std;
int main(int argc, char** argv)
{
ifstream file(argv[1]);
istream_iterator<string> my_it(file);
for (; my_it != istream_iterator<string>(); my_it++)
printf("%s\n", (*my_it).c_str());
}
但是我如何结合这两者,以便通过简单的(argc == 2)
检查使我可以使用文件流或stdin初始化输入流迭代器,然后继续我的快乐方式?
But how do I combine these two so that a simple (argc == 2)
check lets me initialize my input stream iterator with either a file stream or stdin and go on about my merry way?
推荐答案
您可以在构造迭代器后将其分配给它:
You can assign to the iterator after constructing it:
int main(int argc, char** argv)
{
ifstream file;
istream_iterator<string> my_it;
if(argc == 2) {
file.open(argv[1]);
my_it = istream_iterator<string>(file);
} else {
my_it = istream_iterator<string>(cin);
}
}
这篇关于使用istream_iterator并从标准输入或文件中读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!