简体   繁体   English

在cpp中将单词从一个文件复制到另一个文件

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

I'm trying to copy words from one file to another in cpp, here's my code : 我正在尝试将单词从一个文件复制到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;
}

this way I get a compilation error : 这样我得到一个编译错误:

expression must have class type

at the line of where I call copy() 在我调用copy()的那一行

If I change the construction of the iterators to the following it works : 如果我将迭代器的构造更改为以下内容,则它会起作用:

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

I thought choosing between () and {} when initializing objects in cpp is just a matter of choice but I guess I'm wrong. 我认为在cpp中初始化对象时在()和{}之间进行选择只是一个选择问题,但是我想我错了。 Can someone explain this to me ? 谁可以给我解释一下这个 ?

In the first code snippet, the set<string> words(istream_iterator<string>(ifs), istream_iterator<string>()) line is parsed as a declaration of a function words that has two parameters: istream_iterator<string> ifs and an unnamed parameter of type istream_iterator<string> and returns a set<string> . 在第一个代码段中,将set<string> words(istream_iterator<string>(ifs), istream_iterator<string>())行解析为具有两个参数的函数words声明: istream_iterator<string> ifs和一个类型为istream_iterator<string>未命名参数,并返回set<string> That's why it gives a compilation error. 这就是为什么它会导致编译错误。 The second one cannot be parsed as a function declaration, so it works properly. 第二个不能解析为函数声明,因此它可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将字符串从一个.cpp文件传输到另一个.cpp文件 - Transferring a string from one .cpp file to another 从一个.cpp文件中找到文件,但从另一个.cpp文件中给出“无此文件或目录” - file found from one .cpp file, but give “No such file or directory” from another .cpp file 从另一个.cpp 文件启动一个.cpp 文件 - Start a .cpp file from another .cpp file CPP从另一个.cpp文件调用函数 - CPP Calling a function from another .cpp file 如何从另一个 .cpp 文件中的一个 .cpp 文件调用函数? - How can I call functions from one .cpp file in another .cpp file? 如何在另一个 cpp 文件中使用 const 对 - How to use a const pair from one cpp file in another 如何在另一个 cpp 文件中使用一个 cpp 文件中的 function? - how can I use a function from one cpp file in another cpp file? 使用从 one.cpp 中的 one.cpp 初始化的 object 在 another.cpp 文件中不带类 - Using an initialized object from one .cpp in another .cpp file without classess 将文本从一个文件复制到另一c ++ fstream时出错 - Error copying text from one file to another c++ fstream 在所有cpp文件中使用一个globe变量。如果cpp文件的一个类更改了值,我想从另一个类cpp文件访问它 - Use one globe variable in all cpp files.If one class of the cpp file changed the value,I want to access it from another class cpp file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM