【发布时间】:2015-05-18 21:19:29
【问题描述】:
我编写了一个程序,它可以加载一个文本文件,可以决定每个单词的长度,并且可以根据单词的长度编写 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;
}
我的目标是我已经将整个单词分类到文件中,唯一的问题是它们会覆盖自己......我该如何摆脱它?
【问题讨论】:
-
向我们展示您目前编写的代码是个好主意...
-
神奇的 8-ball 表示错误在第 42 行或第 73 行,但没有看到您的任何源代码,无法确定是哪一个。
-
如果你想在文件末尾添加,你需要打开它进行追加,对于任何其他情况,你必须打开以进行读写,然后它添加而不移动,只需运行现有单词。
-
对不起,不知道该怎么做:S
标签: c++ file text stringstream