【发布时间】:2017-11-04 19:00:52
【问题描述】:
我想打开一个文件,在每一行末尾附加一个字符串。
我有这个代码:
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
//argv[1] input file
//argv[2] string to add in the end of each line
//argv[3] output file
int main(int argc, char *argv[]){
ifstream open_file(argv[1]);
if (!open_file) {
std::cerr << "Could not open input file\n";
return 0;
}
ofstream new_file(argv[3]);
if (!new_file) {
std::cerr << "Could not create output file\n";
return 0;
}
string s = argv[2];
string str;
while (getline(open_file, str)) {
new_file << str << s << "\n";
}
}
问题是字符串没有添加到每行的末尾。它正在为每个试图附加的字符串创建一个新行。
所以我运行例如:./appendstring.e wordlist.txt hello new_wordlist.txt
这是输出:
我真的不知道我在这里做错了什么。
提前致谢。
【问题讨论】:
-
只是一个提示:读取文件并将
push_back()的每一行添加到std::vector<std::string>,然后将所需的文本附加到每一行。最后,将所有行写回文件。
标签: c++ iostream ifstream ofstream