用c++写入txt文件

write to txt file in c++

我想将随机排序的数据写入文件。我正在使用 g++,但是在 运行 程序之后没有数据保存到文件中。

这是代码:

#include <string>
// basic file operations
#include <stdlib.h>
#include <iostream>
#include <fstream>
using namespace std;

int main() {
    int ra;
    int pp = 0;
    ofstream myfile("fi21.txt");
    myfile.open("fi21.txt");

    for(int j = 0; j < 10; j++)
    {
        for(int i = 0; i < 10; i++)
        {
            ra = (rand()) + pp;
            pp = ra;

            std::string vv;
            vv = "1,";
            vv += i;
            vv += ",";
            vv += ra;
            vv += "\n";

            // myfile << vv;
            myfile.write(vv.c_str(), sizeof(vv));
        }
    }

    //  myfile.close();
    return 0;
}

您的代码 should/could 如下所示:

#include <string>
#include <stdlib.h>
#include <iostream>
#include <fstream>
using namespace std;

int main() {
    int ra;
    int pp = 0;
    ofstream myfile("fi21.txt"); // This already opens the file, no need to call open

    for(int j = 0; j < 10; j++)
    {
        for(int i = 0; i < 10; i++)
        {
            ra = rand() + pp;
            pp = ra;

            // This will concatenate the strings and integers.
            // std::string::operator+= on the other hand, will convert
            // integers to chars. Is that what you want?
            myfile << "1," << i << "," << ra << "\n";
        }
    }

    return 0;
}

那个多余的调用是主要问题,但也请注意您的尝试:

myfile.write(vv.c_str(), sizeof(vv));

有一个错误 - sizeof(vv) 是字节数 std::string 在堆栈中占用的字节数,而不是它的长度。 std::string::lengthstd::string::size 就是为了那个。既然可以 myfile << vv;,为什么还要使用上面的内容?我实际上什至没有在上面的代码中使用 std::string