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

您的问题与 "writing integer to a file" 无关。 你的问题是 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