在 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,它代表追加(它基本上将始终写入文件末尾的整数。我也只是把文字写成一行。
您的问题与"将整数写入文件"无关。 你的问题是 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
相关文章:
- 如何将 txt 文件中的行分隔为组件C++
- 无法打开.txt文件
- 如何使用CLion在Mac上创建一个新的.txt文件
- 使用fstream对txt文件中的数字进行循环
- Visual Studio在尝试读取resource.txt文件时崩溃
- 如何从txt文件中读取多个不同长度的数组?
- 在一次迭代中从 txt 文件中读取多行
- 通过比较C++中的行在 txt 文件中搜索的最简单方法是什么?
- 写入超过 1GB 的.txt文件时出现奇怪的行为
- 视觉 如何循环访问C++中遵循类似格式的多个.txt文件?
- txt 文件中浮点数的最大和最小值
- 从.txt文件中读取浮点型数字并在公式中使用它们
- C++将文本从.txt文件解析为变量
- 在树结构.txt文件中搜索节点
- 为什么我无法打开/读取从 Python 调用的 C 扩展名中的 txt 文件?
- 在 txt 文件中显示前两个数字的程序
- 如何从具有两列的.txt文件创建并行数组?
- 如何使用c ++读取带有非英文字母的*.txt文件?(国际化)
- 如何像在 C++ 中处理数组一样对 .txt 文件中的字符进行寻址?
- 如何读取 TXT 文件并仅将 int 存储在 C 中