Use istream_iterator to loop through a string defined by char pointer : istream iterator « STL Algorithms Iterator « C++






Use istream_iterator to loop through a string defined by char pointer

 
 

#include <iostream>
#include <iterator> 
#include <string>
#include <sstream>
using std::cout;
using std::endl;
using std::istream_iterator;
using std::istringstream;
using std::string;

template <typename Iter> 

double mySum(Iter begin, Iter end) { 
  double sum = 0.0;
  
  for( ; begin != end ;)
    sum += *begin++;
  return sum;
} 

int main() {

  char* stock_ticker = "4.5 6.75 8.25 7.5 5.75";
  
  istringstream ticker(stock_ticker);
  istream_iterator<double> begin(ticker);
  istream_iterator<double> end;

  cout << stock_ticker << endl ;
  
  cout << mySum (begin, end) << endl; 
  return 0;
}

/* 
4.5 6.75 8.25 7.5 5.75
32.75

 */        
  








Related examples in the same category

1.Taking the sum of values from a stream
2.Use istream_iterator to loop through a string
3.Read words from standard input, sort and print out without duplicates
4.Read string from keyboard and save to vector directly
5.Advance istream_iterator