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

C++ Manipulators (endl, setw, setprecision, setf)


นิยาม

Stream Manipulators คือฟังก์ชันที่ออกแบบมาใช้กับ insertion (<<) และ extraction (>>) operators บน stream objects

std::cout << std::setw(10);

ยังสามารถเรียกเป็นฟังก์ชันปกติได้: boolalpha(cout);

Manipulators ใช้เปลี่ยน formatting parameters และแทรก/ดึง special characters

Manipulators ที่ใช้บ่อย

1. endl

เหมือน \n (newline) แต่ยัง flush output stream ด้วย

#include <iostream>
int main() {
    std::cout << "Hello" << std::endl << "World!";
}
Hello
World!

2. showpoint / noshowpoint

ควบคุมการแสดง decimal point ใน floating-point

#include <iostream>
int main() {
    std::cout << "1.0 with showpoint: " << std::showpoint << 1.0 << '\n'
              << "1.0 with noshowpoint: " << std::noshowpoint << 1.0 << '\n';
}
1.0 with showpoint: 1.00000
1.0 with noshowpoint: 1

3. setprecision

เปลี่ยน floating-point precision ต้อง include <iomanip>

#include <iostream>
#include <iomanip>
int main() {
    const long double pi = 3.141592653589793239;
    std::cout << "default precision (6): " << pi << '\n'
              << "std::setprecision(10): " << std::setprecision(10) << pi << '\n';
}
default precision (6): 3.14159
std::setprecision(10): 3.141592654

4. setw

เปลี่ยนความกว้างของ input/output field ถัดไป ต้อง include <iomanip>

#include <iostream>
#include <iomanip>
int main() {
    std::cout << "no setw:" << 42 << '\n'
              << "setw(6):" << std::setw(6) << 42 << '\n'
              << "setw(6), several: " << 89 << std::setw(6) << 12 << 34 << '\n';
}
no setw:42
setw(6):    42
setw(6), several: 89    1234