fork download
  1. /** Print the shortest and the longest whitespace-separated words in the input.
  2.  
  3.   To try:
  4.  
  5.   $ g++ -std=c++11 print-minmax-words.cpp && </usr/share/dict/words ./a.out
  6.   A: 1, electroencephalograph's: 23
  7.  
  8.   >>> import sys
  9.   >>> spaces = [c for c in map(chr, range(sys.maxunicode+1)) if c.isspace()]
  10.   >>> len(spaces)
  11.   29
  12.   >>> spaces[:10]
  13.   ['\t', '\n', '\x0b', '\x0c', '\r', '\x1c', '\x1d', '\x1e', '\x1f', ' ']
  14.   >>> from itertools import count
  15.   >>> with open('input', 'w', encoding='utf-8') as file:
  16.   ... file.write("".join("%02d%c" % (i, s) for i, s in enumerate(spaces)))
  17.   ...
  18.   87
  19.   >>> t = open('input', encoding='utf-8').read()
  20.   >>> len(t)
  21.   87
  22.   >>> len(t.encode())
  23.   123
  24.   >>> max(t.split(), key=len)
  25.   '00'
  26.   >>> min(t.split(), key=len)
  27.   '00'
  28.   >>> min(t.encode().split(), key=len)
  29.   b'00'
  30.   >>> max(map(len, t.encode().split()))
  31.   93
  32.  
  33. */
  34. #include <algorithm> // minmax
  35. #include <iostream>
  36. #include <iterator> // istream_iterator
  37. #include <string>
  38.  
  39. bool size_less(const std::string& a, const std::string& b) {
  40. return a.size() < b.size(); // compare word sizes in bytes
  41. }
  42.  
  43. int main() {
  44. using namespace std;
  45. // skipws is set, the currently imbued locale is used to determine
  46. // whether a charT is whitespace
  47. //NOTE: Windows, OS X, Linux demonstrate different behavior
  48. // - Windows may corrupt even a byte stream (ANSI conversions)
  49. // - OS X might limit available locales (relevant for wide streams)
  50. if (cin.getloc().name() != "C") {
  51. cerr << "warning: what whitespace is depends on locale: '"
  52. << cin.getloc().name() << "'\n";
  53. }
  54. istream_iterator<string> words(cin), eof;
  55. auto p = minmax_element(words, eof, size_less);
  56. if (p.first == eof && p.second == eof) {
  57. cerr << "there are no words in the input\n";
  58. return 1;
  59. }
  60. else if(!(cout << *p.first << ": " << (*p.first).size() << ", "
  61. << *p.second << ": " << (*p.second).size() << endl))
  62. return 2; // I/O error
  63. return cin.eof() ? 0 : 2;
  64. }
  65.  
Success #stdin #stdout 0s 3436KB
stdin
00	01
020304
0506070809 10…11 12 13 14 15 16 17 18 19 20 21 22 23 24
25
26 27 28 
stdout
00: 2, 10…11 12 13 14 15 16 17 18 19 20 21 22 23 24
25
26 27 28 : 93