1

我想做的事:

将记录存储在文件中。这些记录有两点。

time_t rt; //which stores the time the record was entered by the user

除此之外,我还想存储一个字符串。但我不知道字符串的长度。

这将取决于运行时间,并取决于用户输入的字符数。

需要做什么(根据我):

我没有线索。我知道动态内存分配,但不知道如何将其应用于此类问题。

我试过的:

我试图一次从用户那里获取一个字符并将其存储在一个文本文件中(临时)。

ofstream fileObject;

fileObject.open("temp.txt");

for(int j=0;;j++)
{
  ch = _getche();

if( ch == 13)  break; //user has pressed the return key

  fileObject<<ch;
}

然后我使用以下代码找出文件的大小:

fileObject.seekp(0,ios::end);

long pos = fileObject.tellg(); //this is the size of the file

然后我声明了一个文件大小的动态数组。

char * entry;

entry = new char[pos]

在“out”模式下关闭文件并在“in”模式下再次打开它。

fileObject.close();

ifstream fout;

fout.open("temp.txt"); //this is the name of the text file that i had given

然后字符明智我将文本文件的内容复制到字符数组中:

for(int i=0;i<pos;i++)

  fout>>info[i];

info[i] = '\0';

fout.close();

但现在我不知道该怎么做。

我需要你帮助我:

帮助我将此记录作为类对象写入二进制“.dat”文件。

我的规格:

视窗 XP SP 3

IDE:Visual C++ 2010 Express

4

4 回答 4

1

使用std::stringand std::getline, 都来自<string>标题

于 2013-02-25T09:20:57.573 回答
1

我想存储一个字符串。但我不知道字符串的长度。

然后你需要使用std::string而不是预先分配的chars 数组。

struct user_record
{
    time_t rt; //which stores the time the record was entered by the user
    std::string one_string;
};

帮助我将此记录作为类对象写入二进制“.dat”文件。

有许多序列化选项可供您使用。也许最简单的方法是使用标准流操作将其写为纯文本:

std::ostream& operator <<(std::ostream& os, user_record const& ur)
{
    return os << ur.rt << ' ' << ur.one_string;
}

std::istream& operator >>(std::istream& is, user_record& ur)
{
    return is >> ur.rt >> ur.one_string;
}

对于比单行字符串更多的内容,也许您应该研究Boost序列化库。

于 2013-02-25T09:21:13.867 回答
1

如果您使用的是 c++,那么std::string最好。

std::string abc="";
于 2013-02-25T09:21:43.160 回答
1

对字符串有什么限制?以及如何识别用户在字符串中输入了他想要的所有数据?

如果字符串必须是单行,并且我们可以假设“合理”的长度(即它很容易放入内存中),那么您可以使用std::getline将字符串放入 std::string(用于输入),然后定义输出格式,说文件。如果用户字符串可以是多行,您必须定义一个协议来输入它们(这样您就可以知道单个记录何时完成),以及文件的更复杂格式:一个建议是通过分隔记录一个空行(这意味着输入不能包含一个空行),或者使用如下行的记录头:。(Subversion 使用它的一个变体作为它的消息。但是,有更多信息,但时间戳和行数都在那里。)"%Y-%m-%d %H:%M:%S: user string\n""%Y-%m-%d %H:%M:%S line_count\n"commit

于 2013-02-25T09:42:12.537 回答