tags:

views:

166

answers:

2

Hello I have this program which reverses letters I enter. I'm using iostream. Can I do it another way and replace iostream and cin.getline with cin >> X?

My code:

 //Header Files
 #include<iostream>
 #include<string>
 using namespace std;

 //Recursive Function definition which is taking a reference
 //type of input stream parameter.
 void ReversePrint(istream&);

 //Main Function
 int main()
 {
  //Printing
  cout<<"Please enter a series of letters followed by a period '.' : ";

  //Calling Recursive Function
  ReversePrint(cin);

  cout<<endl<<endl;
  return 0;

 }

 //Recursive Function implementation which is taking a
 //reference type of input stream parameter.
 //After calling this function several times, a stage 
 //will come when the last function call will be returned
 //After that the last character will be printed first and then so on. 
 void ReversePrint(istream& cin)
 {
  char c;
  //Will retrieve a single character from input stream
  cin.get(c);

  //if the character is either . or enter key i.e '\n' then
  //the function will return
  if(c=='.' || c=='\n')
  {
   cout<<endl;
   return;
  }

  //Call the Recursive function again along with the
  //input stream as  paramter.
  ReversePrint(cin);

  //Print the character c on the screen.
  cout<<c;
 }
A: 

The preferred process I teach students is: input, process, output. Input all of your data (or as much as possible) into memory first. Process the data in memory. Output the data after processing. This is very efficient and makes for fast programs.

By reading the text into a string or character array, allows for other algorithms to be applied to the data. Since the algorithms operate in memory, they can be written to be more generic and have a higher re-use rate.

Thomas Matthews
+2  A: 

below function gets line from standard input, reverses it and writes to stdout

#include <algorithm>
#include <string>
#include <iostream>

int main()
{
    std::string line;
    std::getline( std::cin, line );
    std::reverse( line.begin(), line.end() );
    std::cout << line << std::endl;
}
Dominic.wig