gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 23:22:25 28 4
gpt4 key购买 nike

我正在编写一个 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com