so I'm having troubles trying to shift my string that the user inputs over by a random number which is generated between 1-10 (for example: input: coffee random number: 3 output: friihh) but I don't know how to move stringed characters. I also need to be able to randomize the letters given (example: input: coffee output: ocefoc) any ideas?
#include <iostream>
#include <string>
#include <algorithm>
#include <random>
#include <iomanip>
char shift_char( char c, std::size_t offset )
{
staticconst std::string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ""abcdefghijklmnopqrstuvwxyz" ;
// locate c in the alphabet
// https://en.cppreference.com/w/cpp/string/basic_string/findconstauto pos = alphabet.find(c) ;
if( pos == std::string::npos ) return c ; // not found, return unchanged
// now we want the character in the alphabet as position pos+offset
// there is a small detail to be taken care of: pos+offset might be out of range
// if we get to the end of the alphabet, we loop back to the beginning of the string
// and continue counting from there onwards
// note: modulo division result is in range [ 0, alphabet.size()-1 ]
return alphabet[ (pos+offset) % alphabet.size() ] ;
}
std::string shift( std::string str, std::size_t offset )
{
// shift each character in string str
// range based loop: http://www.stroustrup.com/C++11FAQ.html#forfor( char& c : str ) c = shift_char(c,offset) ;
return str ;
}
// shuffle the characters randomly
std::string shuffle( std::string str )
{
// random number generator to use for shuffling
// https://en.cppreference.com/w/cpp/numeric/randomstatic std::mt19937 rng( std::random_device{}() ) ;
// https://en.cppreference.com/w/cpp/algorithm/random_shuffle
std::shuffle( str.begin(), str.end(), rng ) ;
return str ;
}
int main()
{
const std::string str = "Coffee Table!" ;
std::cout << "original: " << std::quoted(str) << '\n' ;
const std::size_t offset = 3 ;
const std::string shifted_str = shift( str, offset ) ;
std::cout << " shifted: " << std::quoted(shifted_str) << '\n' ;
const std::string shuffled_str = shuffle(str) ;
std::cout << "shuffled: " << std::quoted(shuffled_str) << '\n' ;
}