ในส่วนนี้ เราจะดูว่า at() function ใน C++ คืออะไร ฟังก์ชัน at() ใช้เพื่อเข้าถึง character ที่ตำแหน่งที่กำหนด
ในโปรแกรมนี้ เราจะ iterate ทุก character โดยใช้ at() function และพิมพ์พวกมันในบรรทัดต่างๆ
ตัวอย่างโค้ด
#include<iostream>
using namespace std;
main() {
string my_str = "Hello World";
for(int i = 0; i<my_str.length(); i++) {
cout << my_str.at(i) << endl; //get character at position i
}
}
ผลลัพธ์
H e l l o W o r l d