簡體   English   中英

在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;
}

您的代碼應該/可能看起來像這樣:

#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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM