[C++] Recursive call (buggy on redirect = extra space)[C++] Recursive call (buggy on redirect = extra space)

👉

Right-Align

Week 22, 2026

#include "allheaders.hpp" #include "main.hpp" using namespace std; //------------------------------------------------[VARIABLES AND FUNCTION DECLS] string challengeStr3; int lineWidth, startingChars, charStep; string space = " "; size_t position = 0; bool firstPass = true; void RightAlign(string& str, int lineWidth, int startingChars, int charStep, int position, int size, int charCount); int main(int argc, char* argv[]) { try { cout << "\nChallenge pass1\n"; challengeStr3 = "We do not inherit the Earth from our ancestors; we borrow it from our children. Every part of this Earth is sacred, and we must care for it as we would care for our own lives - Chief Seattle"; int size3 = challengeStr3.length(); firstPass = true; lineWidth = 20; startingChars = 1; charStep = 1; RightAlign(challengeStr3, lineWidth, startingChars, charStep, 0, size3, 0); cout << "\nChallenge pass2\n"; challengeStr3 = "We do not inherit the Earth from our ancestors; we borrow it from our children. Every part of this Earth is sacred, and we must care for it as we would care for our own lives - Chief Seattle"; firstPass = true; lineWidth = 10; startingChars = 1; charStep = 0; RightAlign(challengeStr3, lineWidth, startingChars, charStep, 0, size3, 0); cout << "\nChallenge pass3\n"; challengeStr3 = "We do not inherit the Earth from our ancestors; we borrow it from our children. Every part of this Earth is sacred, and we must care for it as we would care for our own lives - Chief Seattle"; firstPass = true; lineWidth = 50; startingChars = 50; charStep = -6; RightAlign(challengeStr3, lineWidth, startingChars, charStep, 0, size3, 0); } // end of try catch (const runtime_error& exception) { std::cout << "Msg: " << exception.what() << "\n"; } return 0; } void RightAlign(string& str, int lineWidth, int startingChars, int charStep, int position, int size, int charCount) { if(firstPass) { int A = (lineWidth) - startingChars; for(int a = 0; a <= A; a++) { cout << space; position = A + startingChars; firstPass = false; } cout << "\b"; cout << str.substr(0, startingChars) << "\n"; charCount = startingChars; str.erase(0, charCount); RightAlign(str, lineWidth,startingChars, charStep, position, str.length(), charCount); } else { int A = (lineWidth) - (charStep + charCount); for(int a = 0; a <= A; a++) { cout << space; firstPass = false; } cout << "\b"; cout << str.substr(0, charCount + charStep) << "\n"; position = A ; charCount = lineWidth - position; str.erase(0, charCount); if(str.length() < 1) { return; } if(charCount < 0) { return; } RightAlign(str, lineWidth, startingChars, charStep, position, str.length(), charCount); } return ; }