HDOJ 1048 输入输出 水

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1048

题目虽然说"START"和"END"间是"a single line",但是这一行还是会包含换行的。每次读入一行进行处理。

 

一、用getline函数。

getline的函数原型是:

istream& getline ( istream &is , string &str , char delim );

istream& getline ( istream& , string& );

功能:将输入流is中读到的字符存入str中,直到遇到终结符delim才结束。

对于第一个函数delim是可以由用户自己定义的终结符;对于第二个函数delim默认为 '\n'(换行符)。
#include <iostream>
#include <string>
using namespace std;

char engChars[30] = {"ABCDEFGHIJKLMNOPQRSTUVWXYZ"};
string aLine;

void decipher()
{
    for (int i = 0;i < aLine.length();i ++)
    {
        //是字母才处理
        if (isalpha(aLine[i]))
        {
            int offset = (aLine[i] - 'A' + 26 - 5) % 26;
            aLine[i] = engChars[offset];
        }
    }
}

int main ()
{
    //读入"START"
    while (getline(cin,aLine,'\n'))
    {
        if (aLine == "ENDOFINPUT")
            break;
        //读入一行
        while (1)
        {
            getline(cin,aLine);
            if (aLine == "END")
                break;
            decipher();
            cout << aLine << endl;
        }
    }
    return 0;
}

 二、用gets。

gets的函数原型是:char*gets(char*buffer);

功能:从stdin流中读取字符串,直至接受到换行符或EOF时停止,并将读取的结果存放在buffer指针所指向的字符数组中。换行符不作为读取串的内容,读取的换行符被转换为null值,并由此来结束字符串。

返回值:读入成功,返回与参数buffer相同的指针;读入过程中遇到EOF(End-of-File)或发生错误,返回NULL指针。
#include <iostream>
#include <string>
using namespace std;

const int LEN = 210;
char engChars[30] = {"ABCDEFGHIJKLMNOPQRSTUVWXYZ"};
char aLine[LEN];

void decipher()
{
    for (int i = 0;i < strlen(aLine);i ++)
    {
        //是字母才处理
        if (isalpha(aLine[i]))
        {
            int offset = (aLine[i] - 'A' + 26 - 5) % 26;
            aLine[i] = engChars[offset];
        }
    }
}

int main ()
{
    //读入"START"
    while (gets(aLine))
    {
        if (strcmp(aLine,"ENDOFINPUT") == 0)
            break;
        while (1)
        {
            gets(aLine);
            if (strcmp(aLine,"END") == 0)
                break;
            decipher();
            printf("%s\n",aLine);        
        }
    }
    return 0;
}

 

 
posted @ 2012-08-21 19:58  peaceful  阅读(449)  评论(0)    收藏  举报