std :: string을 파일에 쓰는 방법?


89

std::string사용자로부터 받는 변수 를 파일에 쓰고 싶습니다 . 나는 write()방법을 사용해 보았고 파일에 씁니다. 그러나 파일을 열면 문자열 대신 상자가 표시됩니다.

문자열은 가변 길이 단일 단어입니다. 가 std::string이 적합한 아니면 문자 배열 또는 무언가를 사용해야합니다.

ofstream write;
std::string studentName, roll, studentPassword, filename;


public:

void studentRegister()
{
    cout<<"Enter roll number"<<endl;
    cin>>roll;
    cout<<"Enter your name"<<endl;
    cin>>studentName;
    cout<<"Enter password"<<endl;
    cin>>studentPassword;


    filename = roll + ".txt";
    write.open(filename.c_str(), ios::out | ios::binary);

    write.put(ch);
    write.seekp(3, ios::beg);

    write.write((char *)&studentPassword, sizeof(std::string));
    write.close();`
}

3
코드를 보여주세요. 일반적으로, 경우에 올바르게 사용, std::string이것에 대한 괜찮습니다.
쓸모 없음

2
문자열 객체가 아닌 문자열의 '페이로드'CONTENT를 저장해야합니다 (일반적으로 실제 콘텐츠에 대한 길이와 포인터 만 포함)
Mats Petersson

답변:


124

현재 string-object 의 바이너리 데이터를 파일 에 쓰고 있습니다. 이 이진 데이터는 실제 데이터에 대한 포인터와 문자열 길이를 나타내는 정수로만 구성됩니다.

텍스트 파일에 쓰려는 경우이를 수행하는 가장 좋은 방법은 아마도 ofstream"아웃 파일 스트림"인을 사용하는 것입니다. 정확히 똑같이 동작 std::cout하지만 출력은 파일에 기록됩니다.

다음 예제는 stdin에서 하나의 문자열을 읽은 다음이 문자열을 파일에 씁니다 output.txt.

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

int main()
{
    std::string input;
    std::cin >> input;
    std::ofstream out("output.txt");
    out << input;
    out.close();
    return 0;
}

참고 out.close()여기에 엄격하게이 켜지지되지 않습니다 :의 deconstructor이 ofstream바로 우리를 위해이 문제를 해결할 수는 out범위를 벗어나.

자세한 내용은 C ++ 참조를 참조하십시오. http://cplusplus.com/reference/fstream/ofstream/ofstream/

이제 바이너리 형식으로 파일에 기록해야하는 경우 문자열의 실제 데이터를 사용하여이를 수행해야합니다. 이 데이터를 얻는 가장 쉬운 방법은 string::c_str(). 따라서 다음을 사용할 수 있습니다.

write.write( studentPassword.c_str(), sizeof(char)*studentPassword.size() );

4
줄 바꿈 문자에 문제가 없도록 std :: ios :: binary를 추가해야했습니다
Waddles

21

std::ofstream파일에 쓰기 위해를 사용한다고 가정하면 다음 스 니펫은 std::string사람이 읽을 수있는 형식으로 파일에 씁니다 .

std::ofstream file("filename");
std::string my_string = "Hello text in file\n";
file << my_string;

0

ios::binaryofstream의 모드에서 제거하고 studentPassword.c_str()대신 사용 (char *)&studentPassword하십시오.write.write()

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.