Writing Integers to a .txt file in c++

浪尽此生 提交于 2021-01-27 14:21:37

问题


I am new to C++ and want to write data(integers) on a .txt file. The data is in three or more columns that can be read later for further usage. I have created successfully a reading project but for the writing one the file is created but it is blank. I have tried code samples from multiple sites but is not helping. I have to write results from three different equations as can be seen from the code.

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

Kindly point out the error or suggest a solution.


回答1:


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

Try this: it will write the integers how you want them, i tested it myself.

Basically what I changed is firstly, I initialized all the variables to 0 so you get the right results and with the ofstream, I just set it to std::ios::app, which stands for appending (it basically will write the integers at the end of the file always. I also just made the writing into one line only.




回答2:


Your problem is not concerning "writing integer to a file". Your problem is that j is not initialized and then the code never enters the loop.

I modified you code by initializing j at the start of the loop and the file is written succesfully

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

It outputs a file named "example 1.txt" and containing the following:

0 0 0
1 2 3
2 4 5

If it happens that you do not initialize i, x and y. The code will write into the file anyway, but it will write garbage values as below:

1984827746 -2 314951928
1984827747 0 1
1984827748 2 3


来源:https://stackoverflow.com/questions/45815139/writing-integers-to-a-txt-file-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!