HDU 1321 Reverse Text

来源:互联网 发布:互联网大会 知乎 编辑:程序博客网 时间:2024/05/29 03:58
Problem Description
In most languages, text is written from left to right. However, there are other languages where text is read and written from right to left. As a first step towards a program that automatically translates from a left-to-right language into a right-to-left language and back, you are to write a program that changes the direction of a given text. 
 
Input
The input contains several test cases. The first line contains an integer specifying the number of test cases. Each test case consists of a single line of text which contains at most 70 characters. However, the newline character at the end of each line is not considered to be part of the line.
Output
For each test case, print a line containing the characters of the input line in reverse order.
Sample Input
3Frankly, I don't think we'll make muchmoney out of this scheme.madam I'm adam
 
Sample Output
hcum ekam ll'ew kniht t'nod I ,ylknarF.emehcs siht fo tuo yenommada m'I madam
getline ()函数默认以换行符'\n'终止, 但是得注意输入test case 数量 N 后边有个回车换行被getline接受了,导致第一个接受的是回车换行而非字符串
用栈:看到反转就想到了栈。注意在输入一个实数后,输入一个字符前一定要getchar()。再就是gets()函数用来从标准输入设备(键盘)读取字符串直到换行符结束,但换行符会被丢弃,然后在末尾添加'\0'字符。用cin会遇空格终止,使用scanf("%s",s) 函数输入字符串时存在一个问题,就是如果输入了空格会认为字符串结束,空格后的字符将作为下一个输入项处理,但gets()函数将接收输入的整个字符串直到遇到换行为止
用gets()时一定要声明char数组,不能用string.
#include<iostream>#include<algorithm>#include<stack>#include<string>using namespace std;int main(){int n,i,t;char s[100];char c;stack<char> q;cin>>n;getchar();while(n--){gets(s);t=strlen(s);for(i=0;i<t;i++){q.push(s[i]);}for(i=0;i<t;i++){cout<<q.top();q.pop();}cout<<endl;}return 0;}
用库函数,其实还可以用strrev()直接反转
#include<iostream>#include<algorithm>#include<string>using namespace std;int main(){int n;cin>>n;n++;int k=0;while(n--){string s;getline(cin,s);if(k){reverse(s.begin(),s.end());cout<<s<<endl;}k++;}return 0;}


0 0
原创粉丝点击