Skip to content

Instantly share code, notes, and snippets.

@CompaqDisc
Created January 31, 2019 21:47
Show Gist options
  • Save CompaqDisc/32790591f8867a0bbe51a15a00843bdc to your computer and use it in GitHub Desktop.
Save CompaqDisc/32790591f8867a0bbe51a15a00843bdc to your computer and use it in GitHub Desktop.
Print std::string various ways.
// For std::string
#include <string.h>
// For std::copy, std::for_each
#include <algorithm>
// For std::ostream_iterator
#include <iterator>
// For std::cin, std::cout
#include <iostream>
// For std::numeric_limits
#include <limits>
int main()
{
char inputChar;
std::string input;
do
{
// Get input
std::cout << "Type a string of text:" << std::endl;
std::getline(std::cin, input);
// Normal
std::cout << "Printing forwards:" << std::endl;
std::cout << input << std::endl;
// Backwards
std::cout << "Printing backwards:" << std::endl;
std::copy(input.rbegin(), input.rend(), std::ostream_iterator<char>(std::cout));
std::cout << std::endl;
// Vertical
std::cout << "Printing vertically:" << std::endl;
std::for_each(input.begin(), input.end(), [](const char &c) {std::cout << c << std::endl;});
// Triangle
std::cout << "Printing as a triangle" << std::endl;
for (std::size_t i = 0; i <= input.length(); i++) {
for (auto c : input.substr(0, i)) {
std::cout << c;
}
std::cout << std::endl;
}
// Length
std::cout << "Length of string: " << input.length() << std::endl;
// Again?
std::cout << "Type another string? (y/N)" << std::endl;
std::cin >> inputChar;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
} while (inputChar == 'y');
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment