Is there a nice function or a way of inputing values into an array until newline? i kinda don't like doing it with gets(); and then check if index%2 is 0 and then if it is i store the int(); value of the char - 48 into a new array. Please, someone, tell me it's stupid!!

#include <iostream>
#include <string>
#include <sstream>

template< typename T, std::size_t N >
bool read_line_into_array( T (&array)[N], std::istream& istm )
{
  // returns true on success (line has exactly N items)
  // an alternative would be to return the number of items read
  std::string line ;
  if( std::getline( istm, line ) )
  {
    std::istringstream sstm(line) ;
    std::size_t i = 0 ;
    while( ( i<N ) && ( sstm >> array[i] ) ) ++i ;
    return (i==N) && (sstm>>std::ws).eof() ;
  }
  return false ;
}

int main()
{
  int a[8] ;
  std::cout << read_line_into_array( a, std::cin ) << '\n' ;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.