在C ++中将整数写入.txt文件

时间:2017-08-22 10:26:50

标签: c++ fstream ofstream file-writing

我是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;
}

请指出错误或提出解决方案。

3 个答案:

答案 0 :(得分:2)

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,它代表追加(它基本上会写总是在文件末尾的整数。我也只是把写作写成一行。

答案 1 :(得分:0)

使用前初始化j

所以,你的for循环将是:

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

您需要使用默认值初始化ixy,例如0
 否则,你会得到垃圾值。

答案 2 :(得分:0)

您的问题与“将整数写入文件”无关。 您的问题是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