2012-08-08 114 views
0

我正在写一个C++代码,其中我动态地创建了一个字符串数组。我写了函数来输出字符串数组中的项目数以及数组本身。接下来我想做的是将数组的元素存储在文本文件中,但是当我打开已写入的文件时,只有数组的最后一个元素出现。下面是我在做什么的样本:字符串输出文件的数组

int num_elem = ReadNumElem(); // my function that gets the number of elements in the array of strings 

string *MyStringArray = ReadNames(num_elem); // my function that reads a file and outputs the necessary strings into the array 

for(int i = 0; i < num_elem < ++i) { 
    ofstream ofs("C:\\Test\\MyStrings.txt") 
    ofs << MyStringArray[i] << endl; // I also tried replacing endl with a "\n" 
} 

我是新的C++,所以我道歉,如果这是太简单了,但我一直在寻找了一段时间,现在,我似乎无法找到一个办法。前两个函数不相关,我只需要知道如何将数据输出到文本文件中,以便所有数据都显示出来,而不仅仅是数组中的最后一个元素。谢谢!

+0

简单的答案是,你应该指定'的std ::的ios_base :: app'在你的'mode'参数传递给'ofstream'构造一个标志,如 'std :: ofstream ofs(“C:\\ Test \\ MyStrings.txt”,std :: ios_base :: out | std :: ios_base :: app);' – oldrinb 2012-08-08 20:11:25

+0

从长远来看可以帮助你的答案是在循环之外打开文件一次。 – oldrinb 2012-08-08 20:11:54

回答

1

您需要声明该文件的循环

编辑


对不起,我不是故意的一个线接听之外,但它已反正现在完成。

3

您每次在数组中打开文件并覆盖其内容。

尝试:

ofstream ofs("C:\\Test\\MyStrings.txt");  
for(int i = 0; i < num_elem < ++i) { 

    ofs << MyStringArray[i] << endl; // I also tried replacing endl with a "\n" 
} 
ofs.close();