OP 所称的“某物”通常称为 Sentinel 或 Canary 值。要用作哨兵,您必须找到数据流中不存在的模式。这很难,因为几乎任何东西都可以在字符串中。如果您使用“XxXxXx”作为您的标记,那么您必须非常小心,不要将其写入文件。
这里可以使用转义字符(查找)的概念,但更好的方法可能是在文件开头存储存储字符串的计数。考虑一个看起来像的输出文件
4
string a1_1
string a1_2
string a1_3
string a1_4
2
string a2_1
string a2_2
读取 cont, 四,然后读取 count 个字符串,然后读取下一个 count,然后读取 count more 个字符串
好吧,所以你觉得他很烂。我不能只在 a1 中插入一个新字符串而不更改文件前面的数字。
好吧,祝你好运,将数据插入文件中间而不会完全弄乱文件。可以这样做,但只有在插入后的所有内容都按插入的大小移动之后,这并不像听起来那么简单。在编程生涯中,这是分配给您的那种任务,并且您必须寻求帮助,您几乎注定要将文件读入内存,插入新值并将文件写回又出来了,所以就随它去吧。
那么这在代码中是什么样的呢?首先,我们放弃数组,转而使用std::vector
. 向量很聪明。他们成长以适应。他们知道里面有多少东西。他们照顾好自己,所以没有不必要new
的delete
废话。你一定是愚蠢的不使用它们。
阅读:
std::ifstream infile(file name);
std::vector<std::string> input;
int count;
if (infile >> count)
{
infile.ignore(); // discard end of line
std::string line;
while (input.size() < count && getline(infile, line))
{
input.push_back(line);
}
if (input.size() != count)
{
//handle bad file
}
}
else
{
// handle bad file
}
和写作
std::ofstream outfile(file name);
if(outfile << output.size())
{
for (std::string & out: output)
{
if (!outfile << out << '\n')
{
// handle write error
}
}
}
else
{
// handle write error
}
但这看起来像家庭作业,所以 OP 可能不允许使用一个。在这种情况下,逻辑是相同的,但你必须
std::unique_ptr<std::string[]> inarray(new std::string[count]);
或者
std::string * inarray = new std::string[count];
为您正在读取的字符串分配存储空间。第二个看起来比第一个工作量少。外表是骗人的。第一个为你照顾你的记忆。第二个要求您的代码中至少有一个delete[]
以正确的速度存放内存。错过它,你就会有内存泄漏。
您还需要有一个变量来跟踪数组的大小,因为指针不知道它们所指向的大小。这使得写for
循环不太方便。