c++ - 循环写入文件时出现问题

标签 c++

这里我有两段 C++ 代码,它们应该将一些数据写入文件。第一个在下面并且有效:

void ParameterManager::Save()
{
    std::ofstream saveFile;
    saveFile.open(path, std::ios::trunc | std::ios::out);
    if (saveFile.is_open())
    {
        saveFile << "File opened. Begin saving.\n";
        for (int i = 0; i < 4; ++i)
        {
            saveFile << "Hoppa" << std::endl;
        }
     }
     saveFile.close();
}

输出文件的结果是:

File opened. Begin saving.
Hoppa
Hoppa
Hoppa
Hoppa

如预期。 第二个在下面,但它不起作用:

void ParameterManager::Save()
{
    std::ofstream saveFile;
    saveFile.open(path, std::ios::trunc | std::ios::out);
    if (saveFile.is_open())
    {
        saveFile << "File opened. Begin saving.\n";
        for (auto item : map)
        {
            std::cout << "Hoppa" << std::endl;
            saveFile << "Hoppa" << std::endl;
        }
     }
     saveFile.close();
}

其中映射是包含 4 个条目的 HashMap ,它是实现函数 Save 的类的成员。输出文件中的结果是:

File opened. Begin saving.

Hoppa 行在终端中打印但从未写入文件。我在 Debug模式下验证并执行写入 4 次,但内容未写入文件。 我在虚拟机 windows 7 pro 上测试它。主机是MacBookPro。我使用 Visual Studio 2013 Pro。 你能帮我理解为什么第二个版本的代码不能像预期的那样工作吗? 非常感谢你们所有人。

最佳答案

好吧,我不知道,但是当我使用 std::map<int, int> 时它会起作用并输入 4 std::pair<int, int>并使用相同的 for循环:

http://coliru.stacked-crooked.com/a/e694252e96aebab5

#include <iostream>
#include <fstream>
#include <string>
#include <map>

void save()
{
    std::map<int, int> mappa;

    for (size_t i = 0; i < 4; ++i) {
        mappa.insert(mappa.begin(), std::pair<int, int>(i,i));   
    }

    std::ofstream saveFile;
    saveFile.open("test.txt", std::ios::trunc | std::ios::out);
    if (saveFile.is_open())
    {
        saveFile << "File opened. Begin saving.\n";
        for (auto it : mappa)
        {
            saveFile << "Hoppa" << std::endl;
            std::cout << "PRINTED LINE" << std::endl;
        }
     }
     saveFile.close();
}

int main() {
    save();
}

关于c++ - 循环写入文件时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33028701/

相关文章:

c++ - 将 g++ 4.8 链接到 libstdc++

c++ - 从用户获取目录

c++ - 为什么两个函数有相同的地址?

c++ - 使用 strtok_s 显示文本文件中的文本

c++ - 输入命令作为另一个应用程序的参数

c++ - 视差映射中的立体视觉

c++ - 关于在构造函数中将临时绑定(bind)到引用成员的虚假警告

c++ - 毫秒计时C++

c++ - 我可以从 double 期望什么精度?

c++ - 无法在 cpp 中绑定(bind)运算符 <<