C ++如何将字符串添加到现有文本文件而不覆盖它?
C++ How do i add a string to an existing text file without overwriting it?
我编写了一个程序,可以加载一个文本文件,可以决定每个单词的长度,并可以根据单词的长度编写txt文件。但是当我 运行 程序时,新的文本文件总是只填充一个单词(每个新单词都有一个已经存在的文本文件的长度只是覆盖文本文件)
起始文本文件如下所示():
http://i.stack.imgur.com/WBaRf.png
在我 运行 编写程序后,我新创建的文本文件(以其长度命名,例如:7.txt):
http://i.stack.imgur.com/6QKgE.png
我的代码:
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main(int argc, char *argv[])
{
char filename[128];
ifstream file;
char line[100];
cout << "Input filename: " << flush;
cin.getline(filename, 127);
file.open(filename, ios::in);
if (file.good())
{
file.seekg(0L, ios::beg);
int number = 0;
while (!file.eof())
{
file.getline(line, 100);
stringstream stream;
stream << line;
number++;
cout <<"Number: "<< number << " length: " << stream.str().length() << " " << line << endl;
std::stringstream sstm;
int laenge = stream.str().length();
string txt = ".txt";
sstm << laenge << txt;
string result = sstm.str();
std::ofstream outFile(result);
outFile << line << endl;
outFile.close();
}
}
else
{
cout << "File not found" << endl;
}
while (true)
{
};
return 0;
}
我的目标是将整个单词分类到文件中,唯一的问题是它们会覆盖自己...我怎样才能摆脱它?
如果不想覆盖文件内容,可以打开文件并指定要追加到文件中:
std::ofstream outFile(result, ios::app);
// ^^^^^^^^
我编写了一个程序,可以加载一个文本文件,可以决定每个单词的长度,并可以根据单词的长度编写txt文件。但是当我 运行 程序时,新的文本文件总是只填充一个单词(每个新单词都有一个已经存在的文本文件的长度只是覆盖文本文件)
起始文本文件如下所示():
http://i.stack.imgur.com/WBaRf.png
在我 运行 编写程序后,我新创建的文本文件(以其长度命名,例如:7.txt):
http://i.stack.imgur.com/6QKgE.png
我的代码:
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main(int argc, char *argv[])
{
char filename[128];
ifstream file;
char line[100];
cout << "Input filename: " << flush;
cin.getline(filename, 127);
file.open(filename, ios::in);
if (file.good())
{
file.seekg(0L, ios::beg);
int number = 0;
while (!file.eof())
{
file.getline(line, 100);
stringstream stream;
stream << line;
number++;
cout <<"Number: "<< number << " length: " << stream.str().length() << " " << line << endl;
std::stringstream sstm;
int laenge = stream.str().length();
string txt = ".txt";
sstm << laenge << txt;
string result = sstm.str();
std::ofstream outFile(result);
outFile << line << endl;
outFile.close();
}
}
else
{
cout << "File not found" << endl;
}
while (true)
{
};
return 0;
}
我的目标是将整个单词分类到文件中,唯一的问题是它们会覆盖自己...我怎样才能摆脱它?
如果不想覆盖文件内容,可以打开文件并指定要追加到文件中:
std::ofstream outFile(result, ios::app);
// ^^^^^^^^