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

相關文章
相關標籤/搜索