c++ - 为什么第二个功能不等待用户输入?

标签 c++ gcc stdin

我的 main.cpp 调用了两个函数来对整数进行排序,这些函数由用户在 stdin 中给出。

问题::SortIteratorAdaptor() 的调用工作正常,但随后没有等待用户在 SortVector() 中输入就退出了。 我认为,这是由于 EOF 位于 stdin 导致第二个 std::cin 退出而不等待用户输入.如果是这种情况,在 `stdin 处使用 EOF 的最佳方式是什么?

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>


void SortIteratorAdaptor( void )
{
 std::vector<int> v ;

 std::cout << "Enter SortIterator Elems\n" ;
 std::copy(std::istream_iterator<int> (std::cin),std::istream_iterator<int> (),\ 
 std::back_insert_iterator<std::vector<int> > (v) ) ;

 std::sort( v.begin(), v.end() ) ;

 std::cout << "Sorted Elems Are:\n" ;
 std::copy( v.begin(), v.end(), std::ostream_iterator<int> (std::cout, "\n") ) ;

 return ;
} 

void SortVector( void )
{
 std::vector<int> v ;

 int n = 0 ;
 std::cout << "Enter Vector elements, Press Ctrl+D to break std::cin\n" ; 
 while( std::cin >> n ) v.push_back( n ) ;

 std::cout << "\n" << "Sorted Elems Are:\n" ;
 std::sort( v.begin(), v.end() ) ;
 for( n = 0; n < v.size(); n++ ) std::cout << v[n] << "\n" ;

 std::cout << "\n\n" ;
 return ;
} 

int main( int argc, char** argv )
{
 std::cout << "Begin Sort Ints with Iterator_Adaptors and vectors\n" ;
 SortIteratorAdaptor() ;

 std::cout << "Begin Sort Ints with vectors\n" ;
 SortVector() ;

 std::cout << "Exiting..." ; 
 return 0 ;
} 

最佳答案

声音就像在使用 std::cin 执行 std::copy() 之后使输入流处于失败状态(这没关系,否则复制循环将结束)。

放一个

std::cin.clear();

在此行之后(另见 std::istream::clear())。

关于c++ - 为什么第二个功能不等待用户输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23562342/

相关文章:

linux - 强制 gcc 在 64 位平台上编译 32 位程序

c - 用于保持地址原样的 gcc 命令?

node.js - Node : write to stdin of bash process crashes with EPIPE

bash - bash select menu 的正确使用方法和一起阅读

ruby - 如何立即打印标准输出?

c++ - 计算字符串中的字符串

c++ - 为什么 gcc 不发出格式警告?

c++ - 为什么 C++ 中类的大小取决于数据成员的公共(public)/私有(private)状态?

c++ - C++ 中的数据成员偏移量

c - 错误 : libtool - while compiling an MPI program