c语言cin读取一行txt,如何从cin中读取C ++中的EOF

你可以从stdin读取可变数量的数据的唯一方法是使用循环。 我总是发现std::getline()函数工作得很好:

std::string line; while (std::getline(std::cin, line)) { std::cout << line << std::endl; }

默认情况下getline()读取直到换行。 你可以指定一个替代的终止字符,但是EOF本身不是一个字符,所以你不能简单地对getline()进行一次调用。

您可以通过使用stream迭代器而不显式循环来完成。 我确定它在内部使用某种循环。

#include #include #include #include #include int main() { // don't skip the whitespace while reading std::cin >> std::noskipws; // use stream iterators to copy the stream to a string std::istream_iterator it(std::cin); std::istream_iterator end; std::string results(it, end); std::cout << results; }

使用循环:

#include using namespace std; ... // numbers int n; while (cin >> n) { ... } // lines string line; while (getline(cin, line)) { ... } // characters char c; while (cin.get(c)) { ... }

资源

在使用std::istream_iterator研究了KeithB的解决scheme之后,我发现了std:istreambuf_iterator 。

testing程序将所有pipe道input读入一个string,然后再写出来:

#include #include #include int main() { std::istreambuf_iterator begin(std::cin), end; std::string s(begin, end); std::cout << s; }

可能最简单和一般高效:

#include int main() { std::cout << std::cin.rdbuf(); }

如果需要,可以使用其他types的stream,如std::ostringstream作为缓冲区,而不是标准输出stream。

你可以使用std :: istream :: getline() (或者最好是在std :: string上工作的版本 )来获得一整行。 两者都有允许您指定分隔符(行尾字符)的版本。 string版本的默认值是'\ n'。

可悲的一面是:我决定使用C ++ IO来与基于boost的代码保持一致。 从这个问题的答案我selectwhile (std::getline(std::cin, line)) 。 在cygwin(mintty)中使用g ++版本4.5.3(-O3),我得到了2 MB / s的吞吐量。 Microsoft Visual C ++ 2010(/ O2)为相同的代码提供了40 MB / s。

在while (fgets(buf, 100, stdin))重写IO到纯C之后while (fgets(buf, 100, stdin))吞吐量在两个testing编译器中跳到90 MB / s。 这对任何大于10 MB的input都是有效的。

while(std::cin) { // do something }

等等,我是否正确地理解你? 你使用cin键盘input,并且当用户inputEOF字符时,你想停止阅读input? 为什么用户inputEOF字符? 或者你的意思是你想停止从EOF文件中读取?

如果你真的想用cin来读取EOF字符,那么为什么不直接指定EOF作为分隔符呢?

// Needed headers: iostream char buffer[256]; cin.get( buffer, '\x1A' );

如果您的意思是停止从EOF文件中读取数据,则只需使用getline并再次指定EOF作为分隔符。

// Needed headers: iostream, string, and fstream string buffer; ifstream fin; fin.open("test.txt"); if(fin.is_open()) { getline(fin,buffer,'\x1A'); fin.close(); }

一个select是使用一个容器,例如

std::vector data;

并将所有inputredirect到这个集合中,直到收到EOF ,

std::copy(std::istream_iterator(std::cin), std::istream_iterator(), std::back_inserter(data));

但是,被使用的容器可能需要经常重新分配内存,否则当系统内存不足时,将以std::bad_allocexception结束。 为了解决这些问题,你可以保留一个固定数量的元素,并单独处理这些数量的元素,即

data.reserve(N); while (/*some condition is met*/) { std::copy_n(std::istream_iterator(std::cin), N, std::back_inserter(data)); /* process data */ data.clear(); }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值