fork download
  1. #include <iostream>
  2. #include <strstream>
  3. #include <fstream>
  4. #include <set>
  5. #include <string>
  6.  
  7. typedef std::set<std::string> fset;
  8.  
  9.  
  10. //пересечение множеств
  11. void intersect(std::ostream& _o,
  12. const fset& a, const fset& b){
  13. fset::const_iterator p1 = a.begin();
  14. fset::const_iterator p2 = b.begin();
  15. while((p1 != a.end()) && (p2 != b.end())){
  16. if(*p1 < *p2)
  17. ++p1;
  18. else {
  19. if(*p1 == *p2){
  20. _o << *p1 << std::endl;
  21. ++p1;
  22. }
  23. ++p2;
  24. }
  25. }
  26. _o.flush();
  27. }
  28.  
  29.  
  30. //пересечение входных потоков
  31. void str_intersect(std::ostream& _o,
  32. std::istream& _i1,
  33. std::istream& _i2){
  34. fset sa, sb;
  35. std::string s;
  36.  
  37. while(std::getline(_i1, s) && ! _i1.fail())
  38. sa.insert(s);
  39.  
  40. while(std::getline(_i2, s) && ! _i2.fail())
  41. sb.insert(s);
  42.  
  43. intersect(_o, sa, sb);
  44. sa.clear();
  45. sb.clear();
  46. }
  47.  
  48.  
  49. int main(void){
  50. // для примера
  51. char s1[] = "Здравствуйте, нужно записать\n"\
  52. "в text3.txt строки, которые\n"\
  53. "есть и в text1.txt, и в text2.txt\n"\
  54. "помогите, пожалуйста.\n"\
  55. "конец";
  56. std::istrstream sp1(s1);
  57.  
  58. char s2[] = "Здравствуйте, нужно записать\n"\
  59. "в text8.txt СТРОКИ, которые, \n"\
  60. "есть и в text1.txt, и в text2.txt\n"\
  61. "помогите мне, пожалуйста!\n"\
  62. "конец";
  63. std::istrstream sp2(s2);
  64.  
  65. str_intersect(std::cout, sp1, sp2);
  66.  
  67. /* работа с файлами
  68. std::ifstream f1("file1.txt");
  69. std::ifstream f2("file2.txt");
  70. std::ofstream f3("result.txt");
  71. str_intersect(f3, f1, f2);
  72. f1.close();
  73. f2.close();
  74. f3.close();
  75. */
  76. return 0;
  77. }
  78.  
Success #stdin #stdout 0s 3276KB
stdin
Standard input is empty
stdout
Здравствуйте, нужно записать
есть и в text1.txt, и в text2.txt
конец