ifelse 测试-C++ Primer Plus

该书中有一个好玩的打印

case 1:

#include <iostream>


int main()
{
        char ch; 

        std::cout << "Type, and I shall repeat.\n";
        std::cin.get(ch);


        while (ch != '.')
        {   
                if (ch == '\n')
                        std::cout << ch; 
                else
                        std::cout << ++ch;

                std::cin.get(ch);
        }   

        std::cout << "\nPlease excuse the slight confusion\n";

        return 0;
}

执行结果:ios

由于++ch,因此打印的是输入的下一个字符。spa

case 2:

使用ch+1代替++chcode

#include <iostream>


int main()
{
        char ch; 

        std::cout << "Type, and I shall repeat.\n";
        std::cin.get(ch);


        while (ch != '.')
        {   
                if (ch == '\n')
                        std::cout << ch; 
                else
                        std::cout << ch + 1;

                std::cin.get(ch);
        }   

        std::cout << "\nPlease excuse the slight confusion\n";

        return 0;
}

执行结果:ci

发现输入的是字符,输出的是字符对应的ascii码,缘由是加法操做使char型提高为int。get

case 3:

打印chio

#include <iostream>


int main()
{
        char ch; 

        std::cout << "Type, and I shall repeat.\n";
        std::cin.get(ch);


        while (ch != '.')
        {   
                if (ch == '\n')
                        std::cout << ch; 
                else
                        std::cout << ch; 

                std::cin.get(ch);
        }   

        std::cout << "\nPlease excuse the slight confusion\n";

        return 0;
}

 

结果:class

相关文章
相关标签/搜索