TEST.CPP
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream in("document1.txt");
ofstream out("document2.txt");
string str;
while(getline(in,str))
out<<str<<endl;
}
document1.txt
aaaaaaaa
bbb bbb
c c c c
d
下命令行,你可以做
$g++ test.cpp -o test.out
$test.out
,然後你會得到document2.txt
aaaaaaaa
bbb bbb
c c c c
d
P.S.在Mac和Linux下測試的所有代碼
P.S.如果將第9行test.cpp從out<<str<<endl;
更改爲out<<str;
document2。TXT會變得
aaaaaaaabbb bbbc c c cd
因爲getline(in,str)
函數將提取從in
字符,並將它們存儲到str
直到「\ n」或結束文件被發現。
這意味着str
不包含'\ n'。你需要自己添加'\ n'。
P.S.下C++,如LihO說,你並不需要關閉in
和out
,因爲in
和out
將在第10行}
此外,當您執行第9行,你不需要衝洗被關閉,因爲endl
有清洗功能。
您是否檢查文件是否實際打開? –
你並沒有明確地關閉流,所以它們不會被刷新/關閉,直到它們超出範圍。這是你的整個程序,還是其他的事情發生之後? – benjymous
@阿里阿拉米里。感謝您的回覆。我在開始時手動創建了它們。這可能是問題嗎? – Simplicity