Search code examples
c++outputasciicoutmalformed

Malformed output when outputting text converted to ASCII with cout, C++


I'm working on a simple in terminal game. But when i try to output some to ASCII converted text. I get malformed output.

code;

    cout << "   _________    _____   ____     _______  __ ___________ "<<'\n';
    cout << " / ___\__  \  /     \_/ __ \   /  _ \  \/ // __ \_  __ \ "<<'\n';
    cout << " / /_/  > __ \|  Y Y  \  ___/  (  <_> )   /\  ___/|  | \/"<<'\n'; 
    cout << " \___  (____  /__|_|  /\___  >  \____/ \_/  \___  >__|   "<<'\n';
    cout << "/_____/     \/      \/     \/                   \/       "<<'\n';

output:

      _________    _____   ____     _______  __ ___________
     / _____    /     _/ __    /  _   / // __ _  __
     / /_/  > __ |  Y Y    ___/  (  <_> )   /  ___/|  | /
   ___  (____  /__|_|  /___  >  ____/ _/  ___  >__|
    /_____/     /      /     /                   /

Solution

  • C++ uses \ in strings as an escape character, so it's not displayed directly, but you'll have to use \\ to display a backslash. The downside of this is that your strings might look very different to the program output after that:

    std::cout << "   _________    _____   ____     _______  __ ___________ "        <<'\n';
    std::cout << " / ___\\__  \\  /     \\_/ __ \\   /  _ \\  \\/ // __ \\_  __ \\ "<<'\n';
    std::cout << " / /_/  > __ \\|  Y Y  \\  ___/  (  <_> )   /\\  ___/|  | \\/"    <<'\n'; 
    std::cout << " \\___  (____  /__|_|  /\\___  >  \\____/ \\_/  \\___  >__|   "   <<'\n';
    std::cout << "/_____/     \\/      \\/     \\/                   \\/       "    <<'\n';
    

    In C++11, raw string literals make life easier. Just wrap your strings like this: R"(yourstring)"

    std::cout << R"(   _________    _____   ____     _______  __ ___________ )"<<'\n';
    std::cout << R"( / ___\__  \  /     \_/ __ \   /  _ \  \/ // __ \_  __ \ )"<<'\n';
    std::cout << R"( / /_/  > __ \|  Y Y  \  ___/  (  <_> )   /\  ___/|  | \/)"<<'\n'; 
    std::cout << R"( \___  (____  /__|_|  /\___  >  \____/ \_/  \___  >__|   )"<<'\n';
    std::cout << R"(/_____/     \/      \/     \/                   \/       )"<<'\n';