#include <string>
#include <iostream>
#include <fstream>
#include <locale>
#include <sstream>
#include <stdexcept>

void read_stream(std::istream& in) 
{
  do {
    int x;
    in >> x;
    if (in.fail()) return;
    std::cout << x << std::endl;
  } while (!in.eof());
}

int main(int argc, char** argv) 
{
  try {
    std::cout << "Finding a ',' in the string \"1,234\" and removing it" << std::endl;
    std::string word("1,234");
    std::string::size_type m = word.find(',');
    if(m != std::string::npos) word.erase(m, 1);
    std::cout << word << std::endl;
    
    std::string lname("en_US");
    if (argc > 1) lname = argv[1];
    std::locale l(lname.c_str()); 
    char c = std::use_facet<std::numpunct<char> >(l).thousands_sep();
    
    std::cout << "Writting a file" << std::endl;
    std::ofstream out("tmp.dat");
    for (size_t i = 0; i < 10; ++i) 
      out << "1" << c << "234" << std::endl;
    out.close();
    
    std::cout << "Reading from file using operator>>(istream&,float&)" << std::endl;
    std::ifstream in("tmp.dat");
    in.imbue(l);
    read_stream(in);
    in.close();
    
    std::cout << "Reading from memory using operator>>(istream&,float&)" << std::endl;
    std::string read("1,234\n1,234\n1,234\n");
    std::stringstream sread(read);
    sread.imbue(std::locale("en_US"));
    read_stream(sread);
  }
  catch (std::exception& e) {
    std::cerr << e.what() << std::endl;
    return 1;
  }
  return 0;
}

