0

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!!

2
Contributors
1
Reply
2
Views
10 Years
Discussion Span
Last Post by vijayan121
0
#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' ;
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.