fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <array>
  4. #include <cstring>
  5.  
  6. template<class e, class t, int N>
  7. std::basic_istream<e,t>& operator>>(std::basic_istream<e,t>& in, const e(&str_lit)[N]) {
  8. std::array<e, N-1> buffer; //get buffer
  9. in >> std::ws; //skips whitespace
  10. if (N)
  11. in.read(&buffer[0], N-1); //read the rest
  12. if (strncmp(&buffer[0], str_lit, N-1)) //if it failed
  13. in.setstate(in.rdstate() | std::ios::badbit); //set the state
  14. return in;
  15. }
  16. template<class e, class t>
  17. std::basic_istream<e,t>& operator>>(std::basic_istream<e,t>& in, const e& char_lit) {
  18. e buffer; //get buffer
  19. in >> buffer; //read data
  20. if (buffer != char_lit) //if it failed
  21. in.setstate(in.rdstate() | std::ios::badbit); //set the state
  22. return in;
  23. }
  24. //redirect mutable char arrays to their normal function
  25. template<class e, class t, int N>
  26. std::basic_istream<e,t>& operator>>(std::basic_istream<e,t>& in, e(&carray)[N]) {
  27. return std::operator>>(in, carray);
  28. }
  29.  
  30. int main()
  31. {
  32. int number;
  33. char character;
  34. char buffer[250];
  35. float thing;
  36. while (std::cin >> "begin " >> number >> 'a' >> character >> buffer >> thing)
  37. std::cout << number << ' ' << character << ' ' << buffer << ' ' << thing << '\n';
  38. std::cout << "Failed to read";
  39. return 0;
  40. }
Success #stdin #stdout 0s 3020KB
stdin
begin 456aPApple 3.14159
begin 789 a Z IMAMUCHLONGERSTRINGWIHTOUTWHITESPACE -9999999
begin 123 b / / 1.0
stdout
456 P Apple 3.14159
789 Z IMAMUCHLONGERSTRINGWIHTOUTWHITESPACE -1e+07
Failed to read