注意:
int N; cin >> N; cin.ignore();
同于
int N; scanf("%d\n",&N);
另:关于 cin 与 scanf:
scanf是格式化输入,printf是格式化输出。
cin是输入流,cout是输出流。效率稍低,但书写简便。
格式化输出效率比较高,但是写代码麻烦。
流输出操作效率稍低,但书写简便。
cout之所以效率低,正如一楼所说,是先把要输出的东西存入缓冲区,再输出,导致效率降低。缓冲区比较抽象,举个例子吧:
曾经就遇到过这样的情况(类似的),
int i;
cout<<‘a‘;
cin>>i;
cout<<‘b‘;
运行结果什么都没看到输出,输入一个整型比如3再按回车后ab同时显示出来了。
但是这样的情况并不是经常发生,是在一些比较大型的工程中偶尔出现,原因是字符a先到了缓冲区,但是没输出,等输入了i,b进入
缓冲区后再一并输出的。
流输入也是差不多的。cin的实时性较差,因为它使用了缓冲区,一般情况下满了才刷新的。
对于字符:cin的输入忽略空格和回车。scanf("%c",&i)等价于i = getchar(),换行符和回车都会被读入。
原题:
1644. Reverse Text
Time Limit: 1.0 Seconds Memory Limit: 65536K
Total Runs: 7899 Accepted Runs: 2891
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 Specification
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 Specification
For each test case, print a line containing the characters of the input line
in reverse order.
Sample Input
3 Frankly, I don‘t think we‘ll make much money out of this scheme. madam I‘m adam
Sample Output
hcum ekam ll‘ew kniht t‘nod I ,ylknarF .emehcs siht fo tuo yenom mada m‘I madam
Source: Western
and Southwestern European Regionals 1996 Practice
源代码:
我的:
1 #include <iostream> 2 #include <cstring> 3 #include <stdio.h> 4 using namespace std; 5 6 char aaa[75]; 7 8 int main() { 9 int N; cin >> N; cin.ignore(); 10 while (N--) { 11 gets(aaa); 12 int len = strlen(aaa); 13 for (int i = len - 1; i >= 0; i--) { 14 cout << aaa[i]; 15 } 16 cout << endl; 17 } 18 return 0; 19 }
网上的:
注意学习其中 reverse 函数:
1 #include<iostream> 2 #include<string> 3 #include<algorithm> 4 using namespace std; 5 6 int main() { 7 8 int cases; 9 cin >> cases; 10 string s; 11 getline(cin, s); 12 while (cases-- && getline(cin, s)) { 13 reverse(s.begin(), s.end()); 14 cout<< s << endl; 15 } 16 return 0; 17 }