2017-04-01 103 views
0

我有一個非常簡單的代碼來創建一個名爲「INPUT.TXT」的文本文件,並使用ostream_iterator寫它:簡單的文件與ostream_iterator寫創建的文件,但不寫

using namespace std; 


int main() 
{ 
    ofstream os{ "Input.txt" }; 
    ostream_iterator<int> oo{ os,"," }; 

    vector<int> ints; 
    for (int i = 0; i < 1000; i++) 
    { 
     ints.push_back(i); 
    } 

    unique_copy(ints.begin(), ints.end(), oo); 

    system("PAUSE"); 
    return 0; 
} 

代碼上面創建一個「Input.txt」,但沒有寫入它。我是否錯過了一些非常明顯和基本的東西

回答

1

你是不是叫system()之前刷新流到磁盤。

您可以明確flush()close()流:

int main() { 
    ofstream os{ "Input.txt" }; 
    ostream_iterator<int> oo{ os,"," }; 

    vector<int> ints; 
    for (int i = 0; i < 1000; i++) { 
     ints.push_back(i); 
    } 

    unique_copy(ints.begin(), ints.end(), oo); 

    os.close(); 

    system("PAUSE"); 
    return 0; 
} 

或者你可以把流周圍劃定範圍括號使其熄滅遲早的範圍。

int main() { 
    { 
    ofstream os{ "Input.txt" }; 
    ostream_iterator<int> oo{ os,"," }; 

    vector<int> ints; 
    for (int i = 0; i < 1000; i++) { 
     ints.push_back(i); 
    } 

    unique_copy(ints.begin(), ints.end(), oo); 
    } 

    system("PAUSE"); 
    return 0; 
} 
0

我想通了,這是因爲我在代碼中有「系統(」暫停「)」,阻止輸出流進入文件。這是工作代碼:

int main() 
{ 
    ofstream os{ "Input.txt" }; // output stream for file "to" 
    ostream_iterator<int> oo{ os,"," }; 

    vector<int> ints; 
    for (int i = 0; i < 1000; i++) 
    { 
     ints.push_back(i); 
    } 

    unique_copy(ints.begin(), ints.end(), oo); 
    return 0; 
} 

不能相信我錯過了這....