输入并存储一个字符串,该字符串可以是用户希望的任意长度

时间:2013-02-25 09:18:41

标签: c++ string memory allocation

我想做什么:

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

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

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

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

需要做什么(据我所知):

我不知道。我知道动态内存分配,但不知道如何将其应用于这样的问题。

我尝试了什么:

我试图从用户那里一次拿一个charachter并将其存储在文本文件中(暂时)。

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]

在“退出”模式下关闭文件,然后在“进入”模式下再次打开文件。

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”文件。

我的规格:

Windows XP SP 3

IDE:Visual C ++ 2010 Express

4 个答案:

答案 0 :(得分:1)

使用std::string标题

中的std::getline<string>

答案 1 :(得分:1)

  

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

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

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;
}

对于比单行字符串更复杂的内容,您可能应该调查Boostserialisation库。

答案 2 :(得分:1)

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

std::string abc="";

答案 3 :(得分:1)

对字符串有什么限制?你好吗? 认识到用户已输入他想要的所有数据 字符串?

如果字符串必须是单行,我们可以假设 然后,“合理的”长度(即它很容易适合记忆) 您可以使用std::getline将字符串转换为 std::string(用于输入),然后定义输出格式, 说"%Y-%m-%d %H:%M:%S: user string\n" 文件。如果用户字符串可以是多行,那么您将拥有 定义一个输入它们的协议(所以你可以知道什么时候 单个记录已完成),以及更复杂的格式 file:一个建议是将记录分隔为空 line(表示输入不能包含空行), 或者使用以下行的记录标题:"%Y-%m-%d %H:%M:%S line_count\n"。 (Subversion使用 它的commit消息的变体。再多一点 但是,信息,但时间戳和行数 在那里。)