还是水题,模拟实现。唯一需要注意的地方就是输出的格式。如果一个单词一个单词的输入,并算出其编码再返回,会遇上PRESENTATION ERROR,因为你永远不知道下一个是不是END,所以你无法决定在该单词的译码输出之后该不该换行。所以用getline函数实现就好了,这样,你可以知道一行输入完毕,输出的时候也就输出一行罢了。
getline
<string>
istream& getline ( istream& is, string& str, char delim ); istream& getline ( istream& is, string& str );
Get line from stream
Extracts characters from is and stores them into str until a delimitation character is found.The delimiter character is delim for the first function version, and '\n' (newline character) for the second. The extraction also stops if the end of file is reached in is or if some other error occurs during the input operation.
If the delimiter is found, it is extracted and discarded, i.e. it is not stored and the next input operation will begin after it.
Notice that unlike the c-string versions of istream::getline , these string versions are implemented as global functions instead of members of the stream class.
Parameters
is istream object on which the extraction operation is performed.str string object where the extracted content is stored.delimThe delimiting character. The operation of extracting successive characters is stopped when this character is read.Return Value
The same as parameter is .Errors are signaled by modifying the internal state flags:
flagerroreofbitThe end of the source of characters is reached during its operations.failbitNo characters were extracted because the end was prematurely found.Notice that some eofbit cases will also set failbit.badbitAn error other than the above happened.
Additionally, in any of these cases, if the appropriate flag has been set with is 's member function ios::exceptions , an exception of type ios_base::failure is thrown.
Example
// getline with strings
#include <iostream>
#include <string>
using namespace std;
int main () {
string str;
cout << "Please enter full name: ";
getline (cin,str);
cout << "Thank you, " << str << ".\n";
}
This example illustrates how to get lines from the standard input stream ( cin ).
Basic template member declarations
template<class charT, class traits, class Allocator>
basic_istream<charT,traits>&
getline (basic_istream<charT,traits>& is,
basic_string<charT,traits,Allocator>& str,
charT delim );
template<class charT, class traits, class Allocator>
basic_istream<charT,traits>&
getline (basic_istream<charT,traits>& is,
basic_string<charT,traits,Allocator>& str );
源代码:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class CodeCipher
{
public:
string WordDecipher(string word)
{
char temp;
string ans;
if (word=="START")
ans="";
else if(word=="END")
ans="";
else
{
for (int i=0;i<word.size();++i)
{
if((word[i]>='A')&&(word[i]<='Z'))
{
temp=(word[i]-'A'-5+26)%26+'A';
ans.push_back(temp);
}
else
ans.push_back(word[i]);
}
}
return ans;
}
void Decipher()
{
string str;
getline(cin,str);
while (str!="ENDOFINPUT")
{
if((str!="START")&&(str!="END"))
cout<<WordDecipher(str)<<endl;
getline(cin,str);
}
}
};
int main()
{
CodeCipher C;
C.Decipher();
return 0;
}