I was beginner to c++ working on a simple string rotation program that would take a number and a string and rotate it about that index in the string. I split the string into 2 sub-strings and then appended they in the right order, however I noticed I got some weird outputs from cout when I tried to append them in the correct order. I could print out the sub-strings separately, and in reverse order, but concatenating them in the correct order would lead to weird prints. If you could point me in the right direction or towards some reference material that would be gratefully appreciated.
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main()
{
int T;
ifstream in( "testInput.txt" );
in >> T;
while( T-- )
{
int r;
string str;
in >> r >> str;
if ( r < 0 ) r = str.size() + r;
string A = str.substr( r ), B = str.substr( 0, r );
cout << "A:" << A << '\n'
<< "B:" << B << '\n'
<< A << B << '\n';
}
}
This code is far more complex than needed (see lastchance's code above for a more succinct method). However with only the change as below to identify the output lines:
which seems to be as required for the first one, and a off-by-1 char split for the second B. However the string append gives what is expected in both cases.
Is your text file correct? Does it have control-code characters in it? Rather than printing A and B as strings, try printing each string as it's ASCII value for each char.