Death420

escape special chars C++

Jul 24th, 2022 (edited)
291
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.38 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <unordered_map>
  4. #include <string>
  5. #include <chrono>
  6. constexpr bool ADD_BENCHMARK_TO_LOG_FILE = true;
  7.  
  8. std::string GetMessageContent()
  9. {
  10.     if(auto file = std::ifstream("message.txt", std::ios::ate))
  11.     {
  12.         size_t size = file.tellg();
  13.         file.seekg(0);
  14.         std::string str(size, ' ');
  15.         file.read(str.data(), size);
  16.         return str;    
  17.     }
  18.     else
  19.     {
  20.         std::cout << "Failed to get the message content.";
  21.         std::exit(0);
  22.     }
  23. }
  24. int main()
  25. {
  26.     const std::unordered_map<char, std::string> map
  27.     {
  28.         {'\\', "\\\\"}, {'`', "\\`"},
  29.         {'*', "\\*"}, {'_', "\\_"}
  30.     };
  31.     const std::string content = GetMessageContent();
  32.  
  33.     auto t1 = std::chrono::high_resolution_clock::now();   
  34.     std::string result;
  35.     result.reserve(content.size() * 1.5);
  36.     for(const char c : content)
  37.     {
  38.         auto it = map.find(c);
  39.         if(it != map.end())
  40.             result += it->second;
  41.         else
  42.             result += c;
  43.     }
  44.     auto t2 = std::chrono::high_resolution_clock::now();
  45.     auto time = std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count();
  46.     std::cout << "It took " << time << " nanoseconds";
  47.     if constexpr(ADD_BENCHMARK_TO_LOG_FILE)
  48.     {
  49.         std::ofstream("log.txt", std::ios::app) << "C++: " << time << " nanoseconds.\n";
  50.     }
  51.     std::cin.get();
  52.     std::cout << "See message content? Y or N\n";
  53.     char c = std::cin.get();
  54.     if(toupper(c) == 'Y')
  55.     {
  56.         std::cout << result << '\n';
  57.     }
  58. }
Add Comment
Please, Sign In to add comment