How can I swap the first and last letters of the input stream in this program?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • davidgambino
    New Member
    • Sep 2014
    • 1

    #1

    How can I swap the first and last letters of the input stream in this program?

    Hi, this is part of an assignment I was given in my introductory programming course. I simply need to know how I could swap the first and last letters of the input in this program:

    Code:
    int main()
    {
    	cout << "---------------------------------------------------------" << endl;
    	cout << "              Letter Swapping Program" << endl;
    	cout << "---------------------------------------------------------" << endl;
    
    	string word;
    	cout << "Please enter a word at least 3 letters long: ";
    	cin >> word;
    	cout << endl << endl;
    
    	int wordLen = word.length();
    	char firstLet = word.at(0);
    	char lastLet = word.back();
    
    	cout << "The length of " << word << "is " << wordLen << endl;
    	cout << "The first and last letters of " << word << " are " << firstLet << " and " << lastLet << " respectively." << endl;
    	cout << "If you swap the first and last letters of this word, you get: ";
    By all means, I know this is a messy program and is not the most concise way to write it, but that's the extent of my knowledge so far in this class.

    Thanks!
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    To swap, move one character to a temp variable while you load the other:

    temp var = first letter;
    first letter = last letter;
    last letter = temp;

    I'm trying to avoid writing the exact code so you can leanr this yourself.

    Comment

    Working...