Learning C++ 之1.3a cout cin endl

std::cout

像之前提到的一樣,cout是將程序輸出到屏幕上的一個標準函數。如下面的例子:

#include <iostream>
 
int main()
{
    std::cout << "Hello world!";
    return 0;
}

爲了輸出多個參數 <<可以使用多次,如下:

#include <iostream>
 
int main()
{
    int x = 4;
    std::cout << "x is equal to: " << x;
    return 0;
}

這個程序的最終輸出結果是:x is equal to : 4

你期望如下函數什麼信息?

#include <iostream>
 
int main()
{
    std::cout << "Hi!";
    std::cout << "My name is Alex.";
    return 0;
}

你可能驚訝於輸出並沒有換行:Hi!My name is Alex.

std::endl

如果你想輸出換行的話,那麼可以考慮使用endl函數。如下:

#include <iostream>
 
int main()
{
    std::cout << "Hi!" << std::endl;
    std::cout << "My name is Alex." << std::endl;
    return 0;
}

輸出結果就是:

Hi!

My name is Alex.

std::cin

std::cin和std::cout相反,std::cout是使用<<操作符向屏幕輸出信息,std::cin是使用>>操作符向屏幕輸入信息。如下面的例子:

//#include "stdafx.h" // Uncomment this line if using Visual Studio
#include <iostream>
 
int main()
{
    std::cout << "Enter a number: "; // ask user for a number
    int x; // no need to initialize x since we're going to overwrite that value on the very next line
    std::cin >> x; // read number from console and store it in x
    std::cout << "You entered " << x << std::endl;
    return 0;
}

你可以編譯執行一下,執行時會先出現如下打印:

Enter a number:

然後你輸入一個數字如:4

那麼就會輸出:

You entered 4

這種方式輸入變量非常簡單,所以以後的課程中我們會經常用到。

std::cin , std::cout , <<  ,>>

新手程序員經常弄混上面幾個符號,下面是一個方便記憶的方法:

  • std::cin和std::cout 往往在語句的左邊
  • std::cout 用來輸出,因爲有out
  • std::cin  用來輸入 ,因爲有in
  • std::cout 使用 <<,將數值從右值輸出到控制檯上
  • std::cin  使用 >>,將數值從控制檯輸出到變量上

個人經驗總結:其實這個符號就是<< >>中國的書名號,先有輸入,再有輸出。中國話和英語往往是反着的所以就是輸入>>,輸出<<.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章