簡體   English   中英

在C ++中將整數寫入.txt文件

[英]Writing Integers to a .txt file in c++

我是C ++的新手,想在.txt文件中寫入數據(整數)。 數據位於三列或更多列中,以后可以讀取以進一步使用。 我已經成功創建了一個閱讀項目,但是對於寫作一個項目,該文件已創建,但是它是空白的。 我嘗試了來自多個站點的代碼示例,但沒有幫助。 從代碼可以看出,我必須根據三個不同的方程式編寫結果。

#include<iostream>
#include<fstream>
using namespace std;

int main ()
{
    int i, x, y;
    ofstream myfile;
    myfile.open ("example1.txt");
    for (int j; j < 3; j++)
    {
        myfile << i ;
        myfile << " " << x;
        myfile << " " << y << endl;
        i++;
        x = x + 2;
        y = x + 1;
    }
    myfile.close();
    return 0;
}

請指出錯誤或提出解決方案。

std::ofstream ofile;
ofile.open("example.txt", std::ios::app); //app is append which means it will put the text at the end

int i{ 0 };
int x{ 0 };
int y{ 0 };

for (int j{ 0 }; j < 3; ++j)
   {
     ofile << i << " " << x << " " << y << std::endl;
     i++;
     x += 2; //Shorter this way
     y = x + 1;
   }
ofile.close()

試試看:它將以您想要的方式寫入整數,我自己對其進行了測試。

基本上我所做的更改是,首先,我將所有變量初始化為0,以便獲得正確的結果,並使用ofstream,我將其設置為std :: ios :: app,它表示追加(它基本上會在以下位置寫入整數)文件的末尾,我也只寫了一行。

使用前初始化j

因此,您的for循環將是:

for (int j = 0; j < 3; j++)
{
    // ...
}

您需要使用默認值(例如0初始化ixy
否則,您將獲得垃圾值。

您的問題與“將整數寫入文件”無關。 您的問題是j未初始化,因此代碼從不進入循環。

我通過在循環開始時初始化j修改了您的代碼,文件成功寫入

#include<iostream>
#include<sstream>
#include<fstream>
#include<iomanip>


using namespace std;

int main ()
{
    int i=0, x=0, y=0;
    ofstream myfile;
    myfile.open ("example1.txt");

    for (int j=0; j < 3; j++)
    {
        myfile  << i ;
        myfile  << " " << x;
        myfile  << " " << y << endl;
        i++;
        x = x + 2;
        y = x + 1;
    }
    myfile.close();
    return 0;
}

它輸出一個名為“ example 1.txt”的文件,其中包含以下內容:

0 0 0
1 2 3
2 4 5

如果發生這種情況,請不要初始化i,x和y。 該代碼無論如何都會寫入文件,但是它將寫入如下的垃圾值:

1984827746 -2 314951928
1984827747 0 1
1984827748 2 3

暫無
暫無

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

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