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

ทำไม std::getline() ถึงข้าม input หลัง formatted extraction?


std::getline() ข้าม input หลัง formatted extraction บางอย่าง เราสามารถตรวจสอบ error นี้จากโค้ดต่อไปนี้ -

ตัวอย่างโค้ด

#include <iostream>
#include <string>
using namespace std;
int main(){
    string name;
    string city;
    if (cin >> name && getline(cin, city)){
        cout << "Your name " << name << " and city " << city;
    }
}

ผลลัพธ์

Amal
Your name Amal and city

เราเห็นว่าโปรแกรมไม่รับ input ที่สอง บางครั้งอาจรับ input ที่สอง แต่ใน output จะแสดงแค่ input แรก ตอนนี้คำถามคือ ทำไมมันพฤติกรรมแบบนี้?

เหตุผลหลักของปัญหานี้คือ เมื่อเราพิมพ์ string แรก แล้วเรากดปุ่ม Enter หรือ Return เมื่อกด Enter หรือ Return มันจะแทรก character '\n' หลังบรรทัดปัจจุบัน Character นี้ก่อให้เกิดปัญหา มัน ignore ส่วนต่อไปของ string

ถ้า name คือ "Amal" แล้วภายในมันจะได้ "Amal\n" เพื่อแก้ปัญหานี้ วิธีหนึ่งคือ เรียก std::cin.ignore() หลัง extraction แรก แล้วมันจะ discard ตัวอักษรที่พร้อมใช้งานถัดไป จึงจะทำงานได้ถูกต้อง