Skip to content

[C++] 基本教學 03: 資料輸入、輸出

不論是什麼程式語言,我們都需要熟練掌握『輸出』(Output)、『輸入』(Input),而在 C++ 中,我們可以透過 <iostream> 標頭檔來掌握基本的 I/O 操作。

iostream,也就是 Input/Output stream (輸入/輸出流)的縮寫。


標準輸出(cout)

cout 是最常見的輸出,可以印出任意資料型態的資料,使用時搭配 << 的符號。

#include <iostream>
#include <string>
using namespace std;


int main() {
    int a = 5;
    float b = 3.3;
    char c = 'a';
    string d = "test";

    cout << "int:    " << a << endl;
    cout << "float:  " << b << endl;
    cout << "char:   " << c << endl;
    cout << "string: " << d << endl;

    return 0;
}



Output:

int:    5
float:  3.3
char:   a
string: test

標準輸入(cin)

cincout 相對,是標準輸入,通常是由鍵盤輸入字串這樣的形式,使用時需搭配 >> 這樣的符號。

#include <iostream>
using namespace std;


int main() {
    // Settings 
    char name[100];

    // Input
    cout << "What's your name?" << endl;
    cin >> name;

    // Output
    cout << "\nYour name is: " << name;

    return 0;
}



Output:

What's your name?
Clay

Your name is: Clay

可以正常印出訊息!不過稍微挑戰一下就會發現,如果輸入的名字有空白,比方說 John Wick,那麼名字就只會印出 John 而已!

要解決這個問題,可能會提到一部分的迴圈觀念,就留到之後來紀錄吧!


printf()

printf() 同樣是將訊息輸出至螢幕上,同時也會回傳輸出的『字元數』。而在 printf() 中若要指定變數作為輸出時,需要搭配所謂的 format specifier

以下列出可以參考的 specifier 表格:

SpecifierOutput
%d, %i有號十進制整數
%u無號十進制整數
%o無號八進制
%x無號十六進制整數
%X無號十六進制整數(大寫)
%f十進制浮點數(小寫)
%F十進制浮點數(大寫)
%e科學記號(小寫)
%E科學記號(大寫)
%g使用最短的形式表示(%e or %f)
%G使用最短的形式表示(%E or %F)
%a十六進制浮點數(小寫)
%A十六進制浮點數(大寫)
%c字符
%s字串
%p指針位址
%%寫入單個 % 符號

以下簡單做個示範:

#include <iostream>
using namespace std;


int main() {
    printf("%%c: %c\n", 'C');
    printf("%%s: %s\n", "Today is a nice day.");
    printf("%%d: %d\n", 10);
    printf("%%f: %f\n", 22.31);
       
    return 0;
}



Output:

%c: C
%s: Today is a nice day.
%d: 10
%f: 22.310000

可以盡情嘗試印印看不同的東西。


scanf()

printf() 相對,scanf() 則是獲取使用者的輸入,並搭配 & 符號取址來指定變數輸入型態。

#include <iostream>
using namespace std;


int main() {
    // Setting
    int num;

    // Input
    printf("Enter a number: ");
    scanf("%d", &num);

    // Output
    printf("Your input is: %d", num);

    return 0;
}



Output:

Enter a number: 100
Your input is: 100

References


Read More

Tags:

Leave a Reply