声明:转载或引用代码请注明 http://blog.csdn.net/fduan/archive/2011/05/11/6411199.aspx
For each list of words, output a line with each word reversed without changing the order of the words.
This problem contains multiple test cases!
The first line of a multiple input is an integer N, then a blank line followed by N input blocks. Each input block is in the format indicated in the problem description. There is a blank line between input blocks.
The output format consists of N output blocks. There is a blank line between output blocks.
Input
You will be given a number of test cases. The first line contains a positive integer indicating the number of cases to follow. Each case is given on a line containing a list of words separated by one space, and each word contains only uppercase and lowercase letters.
Output
For each test case, print the output on one line.
Sample Input
1
3
I am happy today
To be or not to be
I want to win the practice contest
Sample Output
I ma yppah yadot
oT eb ro ton ot eb
I tnaw ot niw eht ecitcarp tsetnoc
分析:此题有三个关键点,一是文件的I/O,二是字符串切割,三是单词的逆序。
下面给出各关键点的实现。
关键一:字符串切割
void split_string( const string & str, std::vector<string> & words ) { words.clear(); typedef string::size_type string_size; string_size i = 0; while( i != str.size() ) { while( i != str.size() && isspace( str[i] ) ) ++i; string_size j = i; while( j != str.size() && !isspace(str[j])) ++j; if( i != j ) { words.push_back( str.substr( i, j - i ) ); i = j; } } }
关键二:单词逆序,借助标准库中的vector和reverse实现。
void reverse_words( const vector<string> & words ) { string word; for( int k = 0; k < words.size() - 1; ++k ) { word = words[k]; reverse( word.begin(), word.end() ); cout << word << " "; } word = words[ words.size() - 1]; if( word.size() > 1 ) reverse( word.begin(), word.end() ); cout << word << endl; }
关键三:文件读取
int main() { ifstream cin("data.txt"); int n; cin >> n; for( int i = 0; i < n; ++i ) { string line; // skip space line getline( cin, line ); int num_lines; cin >> num_lines; for( int j = 0; j < num_lines; ++j ) { vector<string> words; // skip '/n' char c; if( j == 0) c = cin.get(); getline( cin, line ); split_string( line, words ); reverse_words( words ); } if( i < n - 1) cout << endl; } return 0; }