fork download
  1. #include <iostream>
  2. #include <sstream>
  3. #include <string>
  4. #include <cstring>
  5.  
  6. using namespace std;
  7.  
  8. void process (string line, string substring)
  9. {
  10. istringstream linestream(line);
  11.  
  12. int wordcount = 0;
  13. int matchcount = 0;
  14. string first;
  15.  
  16. // Ищем substring в каждом слове
  17. while (!linestream.eof())
  18. {
  19. string word;
  20. linestream >> word;
  21. wordcount++;
  22.  
  23. if (word.find(substring) != string::npos)
  24. {
  25. matchcount++;
  26. if (matchcount == 1) first = word;
  27. }
  28. }
  29.  
  30. // Выводим согласно условию
  31.  
  32. if (matchcount == 0)
  33. {
  34. string reversedline = string(line.rbegin(), line.rend());
  35. // ^ ^ ^ Жуткий на вид хак с итераторами, обращающий строку.
  36. // С ним лучше разобраться.
  37. cout << reversedline << endl;
  38. return;
  39. }
  40.  
  41. if (wordcount == matchcount)
  42. {
  43. cout << line << endl;
  44. return;
  45. }
  46. else // Не все слова имеют подстроку
  47. {
  48. cout << first << endl;
  49. return;
  50. }
  51. }
  52.  
  53. int main ( )
  54. {
  55. while (!cin.eof())
  56. {
  57. string line;
  58. getline(cin, line);
  59. process(line, "foo"); // Ищем "foo"
  60. }
  61. }
  62.  
Success #stdin #stdout 0s 3480KB
stdin
foo bar foo
bar baz quz
foobar barfoo bar
foobar barfoo
stdout
foo
zuq zab rab
foobar
foobar barfoo