2009-12-07 31 views
0

你好,我有这个程序,它反转了我输入的字母。我正在使用iostream。我能否以另一种方式做,并用cin >> X替换iostreamcin.getline如何简化我的C++代码以反转字符?

我的代码:

//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; 
} 
+0

它必须使用相同的递归函数? – Richie 2009-12-07 09:16:13

+0

是使用递归函数来读写 – user172697 2009-12-07 09:22:58

+0

你想传递cin或char缓冲区吗? – 2009-12-07 18:15:58

回答

3

以下功能得到线从标准输入,逆转并写入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; 
}