2013-03-13 134 views
43

我想寫一個std::string變量,我接受從用戶到一個文件。我嘗試使用write()方法,它寫入文件。但是當我打開文件時,我看到的是盒子而不是字符串。如何將std :: string寫入文件?

該字符串只是一個可變長度的單個單詞。是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

請顯示您的代碼。一般來說,正確使用_if_,'std :: string'對此很好。 – Useless 2013-03-13 14:27:02

+1

您需要保存字符串的「有效內容」內容,而不是字符串對象(通常只包含長度和指向實際內容的指針) – 2013-03-13 14:28:25

回答

61

你正在寫在string -object的二進制數據文件。這個二進制數據可能只包含一個指向實際數據的指針和一個表示字符串長度的整數。

如果要寫入文本文件,最好的方法是使用「out-file-stream」ofstream。它的行爲與std::cout完全相同,但輸出寫入文件。

以下示例從標準輸入讀取一個字符串,然後將此字符串寫入文件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()沒有嚴格neccessary此處的ofstream的解構能夠儘快out超出範圍,處理這對我們來說。

欲瞭解更多信息,請參見C++ - 參考:http://cplusplus.com/reference/fstream/ofstream/ofstream/

現在,如果你需要寫一個二進制格式的文件,你應該做這個字符串中使用的實際數據。獲取這些數據的最簡單方法是使用string::c_str()。所以,你可以使用:

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

我必須爲此添加std :: ios :: binary換行符不會有問題 – Waddles 2016-10-31 00:41:08

9

假設你正在使用std::ofstream寫入文件,下面的代碼片段會寫std::string在人類可讀的形式提交:

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

從刪除ios::binary您在您的流中使用studentPassword.c_str()而不是(char *)&studentPassword您的write.write()

相關問題