[英]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::trunc
或fstream::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.