c++ - 输出文件的字符串数组

标签 c++ arrays string outputstream

我正在编写一个 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++ 的新手,如果这太简单了,我深表歉意,但我已经搜索了一段时间,但似乎找不到解决方案。前两个函数不相关,我只需要知道如何将数据输出到文本文件中,以便显示所有数据,而不仅仅是数组中的最后一个元素。谢谢!

最佳答案

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

尝试:

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();

关于c++ - 输出文件的字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11872302/

相关文章:

c++ - 带有 CDT 的 Eclipse 3.7.0 Indigo 显示许多错误的编译错误

C - 单词数组

C++:使用动态内存创建动态数组

swift - 比较带和不带变音符号的阿拉伯字符

java - android-将数组列表转换为自定义格式的一个字符串

c++ - 用最少的探测找到函数的最大值

c++ - 如何访问私有(private)指向类

c++ - 我想一次将十六进制文件读入数组 4 个字节

c - 需要左值作为赋值的左操作数。这意味着什么?

c++ - 如何访问 std::list<string> 中的某个元素