Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม C++ รับและแสดงตัวเลขจากผู้ใช้ (Input/Output)


ใน C++ ใช้ cin สำหรับรับค่า (input) และ cout สำหรับแสดงผล (output)

  • cin - instance ของคลาส istream เชื่อมกับอินพุตมาตรฐาน (คีย์บอร์ด)
  • cout - instance ของคลาส ostream เชื่อมกับเอาต์พุตมาตรฐาน (หน้าจอ)

ตัวอย่างที่ 1: รับตัวเลขเดียว

#include <iostream>
using namespace std;

int main() {
    int num;
    cout << "Enter the number: ";
    cin >> num;
    cout << "The number entered by user is " << num;
    return 0;
}

ผลลัพธ์

Enter the number: 5
The number entered by user is 5

ตัวอย่างที่ 2: รับหลายตัวเลขเก็บใน Array

#include <iostream>
using namespace std;

int main() {
    int a[5], i;
    cout << "Enter the numbers in array: ";
    for (i = 0; i < 5; i++)
        cin >> a[i];
    cout << "The numbers entered by user in array are: ";
    for (i = 0; i < 5; i++)
        cout << a[i] << " ";
    return 0;
}

ผลลัพธ์

Enter the numbers in array: 5 1 6 8 2
The numbers entered by user in array are: 5 1 6 8 2

ใช้ลูป for วนรับค่าและแสดงค่าทีละ element ของอาร์เรย์