【问题标题】:Array of Strings to Output File输出文件的字符串数组
【发布时间】:2012-08-06 00:32:28
【问题描述】:

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

【问题讨论】:

  • 简单的答案是,您应该在 mode 参数中将 std::ios_base::app 指定为 ofstream 构造函数的标志,例如std::ofstream ofs("C:\\Test\\MyStrings.txt", std::ios_base::out | std::ios_base::app);
  • 从长远来看对您有帮助的答案是在循环外打开文件。

标签: c++ arrays string outputstream


【解决方案1】:

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

试试:

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

【讨论】:

    【解决方案2】:

    你需要在循环外声明文件

    编辑


    对不起,我不是要一口气回答,但无论如何现在已经完成了。

    【讨论】:

      猜你喜欢
      • 2017-02-09
      • 1970-01-01
      • 2011-07-08
      • 2021-12-21
      • 2021-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-20
      相关资源
      最近更新 更多