繁体   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