Program Tip

ifstream에서 문자열 변수로 줄 읽기

programtip 2020. 12. 8. 19:50
반응형

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 ); 있지만 문자열 변수에 저장하고 싶습니다. 어떻게 할 수 있습니까?


를 사용 std::getline()에서 <string>.

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

따라서 귀하의 경우에는 다음과 같습니다.

std::getline(read,x);

참고 URL : https://stackoverflow.com/questions/6663131/reading-a-line-from-ifstream-into-a-string-variable

반응형