อ่านบรรทัดจาก ifstream ลงในตัวแปรสตริง

ในรหัสต่อไปนี้:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
    string x = "This is C++.";
    ofstream of("d:/tester.txt");
    of << x;
    of.close();


    ifstream read("d:/tester.txt");
    read >> x;
    cout << x << endl ;
}

Output :

This

เนื่องจากตัวดำเนินการ >> อ่านไม่เกินช่องว่างแรกฉันจึงได้ผลลัพธ์นี้ ฉันจะแยกบรรทัดกลับเข้าไปในสตริงได้อย่างไร

ฉันรู้จักรูปแบบนี้ของ istream& getline (char* s, streamsize n ); แต่ฉันต้องการเก็บไว้ในตัวแปรสตริง ฉันจะทำอย่างไร


person Suhail Gupta    schedule 12.07.2011    source แหล่งที่มา
comment
ดูคำแนะนำที่นี่: stackoverflow.com/questions/116951/   -  person Itamar Katz    schedule 12.07.2011


คำตอบ (1)


ใช้ std::getline() จาก <string>

 istream & getline(istream & is,std::string& str)

ดังนั้นสำหรับกรณีของคุณมันจะเป็น:

std::getline(read,x);
person jonsca    schedule 12.07.2011
comment
ค่าที่ส่งคืนของ getline() (วัตถุสตรีม) ควรได้รับการประเมินในนิพจน์บูล การประเมินบูลของออบเจ็กต์สตรีมเป็นกลอุบายที่สำคัญมากที่นี่: โดยจะประเมิน failbit และ badbit ของสตรีมพื้นฐาน เราควรใช้สิ่งนั้น สามารถดูคำอธิบายเชิงลึกเพิ่มเติมได้ที่นี่: gehrcke.de/2011/06/ - person Dr. Jan-Philip Gehrcke; 18.01.2015