This program allows you to enter a line of text. The text is then passed as an argument to a function. The function builds a new reversed string, one character at a time, using a for loop. The completed string value is then passed back to the main part of the program, which displays it on the screen.
Select and copy the C++ source-code at the bottom of this post.
Here's the code:
#include <iostream> // Using keyboard and screen
using namespace std; // Using standard names cout, cin, endl
// --------------------
string reverse_it( string original )
{
string changed = "";
int last_pos = original.length()-1;
for (int pos = last_pos; pos >= 0; pos--)
changed = changed + original.at( pos );
return changed;
}
// --------------------
int main()
{
cout << "Type in a line of text: ";
// Allow user to type in line of text
string what_i_typed;
getline( cin, what_i_typed );
// Call function to reverse text and display result
cout << reverse_it( what_i_typed );
// Move on to new line on the screen
cout << endl;
return 0;
}
Find out more - buy the book on Amazon...
Select and copy the C++ source-code at the bottom of this post.
Paste into a text editor, such as Nano or Geany.
Then save the new file, ending in .cpp
I used reverse.cpp
To compile from the command-line:
g++ -o reverse.cpp reverse
To run from the command-line:
./reverse
Here's the code:
#include <iostream> // Using keyboard and screen
using namespace std; // Using standard names cout, cin, endl
// --------------------
string reverse_it( string original )
{
string changed = "";
int last_pos = original.length()-1;
for (int pos = last_pos; pos >= 0; pos--)
changed = changed + original.at( pos );
return changed;
}
// --------------------
int main()
{
cout << "Type in a line of text: ";
// Allow user to type in line of text
string what_i_typed;
getline( cin, what_i_typed );
// Call function to reverse text and display result
cout << reverse_it( what_i_typed );
// Move on to new line on the screen
cout << endl;
return 0;
}
Find out more - buy the book on Amazon...