簡體   English   中英

在cpp中將單詞從一個文件復制到另一個文件

[英]Copying words from one file to another in cpp

我正在嘗試將單詞從一個文件復制到cpp中的另一個文件,這是我的代碼:

int main()
{

    string from, to;

    cin >> from >> to;

    ifstream ifs(from);

    ofstream ofs(to);

    set<string> words(istream_iterator<string>(ifs), istream_iterator<string>());
    copy(words.begin(), words.end(), ostream_iterator<string>(ofs, "\n"));

    return !ifs.eof() || !ofs;
}

這樣我得到一個編譯錯誤:

expression must have class type

在我調用copy()的那一行

如果我將迭代器的構造更改為以下內容,則它會起作用:

set<string> words{ istream_iterator<string>{ ifs }, istream_iterator<string>{} };

我認為在cpp中初始化對象時在()和{}之間進行選擇只是一個選擇問題,但是我想我錯了。 誰可以給我解釋一下這個 ?

在第一個代碼段中,將set<string> words(istream_iterator<string>(ifs), istream_iterator<string>())行解析為具有兩個參數的函數words聲明: istream_iterator<string> ifs和一個類型為istream_iterator<string>未命名參數,並返回set<string> 這就是為什么它會導致編譯錯誤。 第二個不能解析為函數聲明,因此它可以正常工作。

暫無
暫無

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

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