سؤال

My main.cpp calls two functions for sorting of integers, given by user at stdin.

Problem:: Call to SortIteratorAdaptor() works perfectly but then exits without waiting for user's input in SortVector(). I think, this happens due to EOF lying at stdin which makes the second std::cin to exit without waiting for user's input. If this is the case, what would be the best way to consume EOF at `stdin?

#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 ;
} 
هل كانت مفيدة؟

المحلول

Sound's like after doing std::copy() with std::cin leaves the input stream in failed state after (which is OK, otherwise the copy loop wouldn't end).

Put a

std::cin.clear();

after this line (also see std::istream::clear()).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top