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

问题描述 投票:0回答:2

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

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

c++ fstream ofstream file-writing
2个回答
5
投票
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,它代表附加(它基本上会写入整数)总是在文件的末尾。我也只写了一行。


2
投票

您的问题与“将整数写入文件”无关。 您的问题是

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
© www.soinside.com 2019 - 2024. All rights reserved.