簡體   English   中英

寫入和讀取文本文件時的垃圾值

[英]Garbage values when writing and reading to a text file

有人可以幫我解決這段代碼的問題嗎? 我得到一堆垃圾價值!

fstream fs("hello.txt");

if(fs.is_open())
{    
    string s = "hello";
    string line;
    fs << s;  

    while(getline(fs,line))
    {
        cout << line;
    }
    cin.get();
}
fs.close();

非常感謝您,但是當我嘗試這樣做時,我得到的卻是同樣的垃圾。 我正在嘗試用world重寫第一個hello並嘗試打印該行

fstream fs("hello.txt");

if(fs.is_open())
{    
    string s = "hello";
    string line;
    fs << s << endl;  
    fs.seekg(0);
    fs << "world" << endl;
    fs.seekg(0);

    while(getline(fs,line))
    {
        cout<<line;
    }
    cin.get();
}
fs.close();

fs的光標位於fs << s之后的文件末尾(將數據正確附加到文件后,這是必需的)。

嘗試調用fs.seekg(0); 將光標移回開頭。

另外,在構造fs時,可能需要提供fstream::truncfstream::app標志。

fstream fs("hello.txt", fstream::in | fstream::out | fstream::trunc);

如果hello.txt在運行程序之前為空,那么它似乎對我有用。 如果文件包含6個或7個字符以上,則您的hello world代碼將使用“ world”覆蓋前6/7個字符,后跟行終止符(取決於平台,可能為1個或2個字符)。 該文件的提醒不會被覆蓋,隨后將在您的getline循環中進行打印。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM