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

Writing Integers to a .txt file in c++

本文关键字:txt 文件 整数 c++      更新时间:2023-10-16

我是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 没有初始化,然后代码永远不会进入循环。

我通过在循环开始时初始化 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;
}

它输出一个名为"示例 1.txt"的文件,其中包含以下内容:

0 0 0
1 2 3
2 4 5

如果碰巧您没有初始化 i、x 和 y。代码无论如何都会写入文件,但它会写入垃圾值,如下所示:

1984827746 -2 314951928
1984827747 0 1
1984827748 2 3