在C ++中将整数写入.txt文件 [英] Writing Integers to a .txt file in c++

查看:90
本文介绍了在C ++中将整数写入.txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++的新手,想在 .txt 文件上写入数据(整数).数据位于三列或更多列中,以后可以读取以作进一步使用.我已经成功创建了一个阅读项目,但是对于写作一个项目,该文件已创建,但是它是空白的.我尝试了来自多个站点的代码示例,但没有帮助.从代码中可以看出,我必须编写来自三个不同方程式的结果.

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.

推荐答案

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.

基本上,我首先将所有变量初始化为0,以便获得正确的结果,并使用ofstream,将其设置为std :: ios :: app,它表示追加(基本上它将写入总是位于文件末尾的整数.我也只写了一行.

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.

这篇关于在C ++中将整数写入.txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆