c++ - 使用 ifstream 读取 .txt 并使用 ofstream 写入新的 .txt 文件,但只有第一行有效
问题描述
我正在尝试读取一个文本文件,text.txt
其中的文本表示十六进制值:
0123456789abcdef
0123456789abcdef
0123456789abcdef
0123456789abcdef
0123456789abcdef
0123456789abcdef
0123456789abcdef
我应该读取这个文件并使用ofstream
写入一个新文件output.txt
来写入这些十六进制值的二进制等价物,-
代表 0 和#
代表 1。
例子:
0 = ----
1 = ---#
2 = --#-
...
F = ####
我的输出output.txt
是
---#--#---##-#---#-#-##--####---#--##-#-#-####--##-####-####
什么时候应该
---#--#---##-#---#-#-##--####---#--##-#-#-####--##-####-####
---#--#---##-#---#-#-##--####---#--##-#-#-####--##-####-####
---#--#---##-#---#-#-##--####---#--##-#-#-####--##-####-####
---#--#---##-#---#-#-##--####---#--##-#-#-####--##-####-####
---#--#---##-#---#-#-##--####---#--##-#-#-####--##-####-####
---#--#---##-#---#-#-##--####---#--##-#-#-####--##-####-####
---#--#---##-#---#-#-##--####---#--##-#-#-####--##-####-####
我的逻辑在那里,但似乎output.txt
只写了text.txt
. 这让我相信我只是在阅读第一行。
我被迫使用 c 风格的字符串,因此我正在读入 char 数组。
这是我的代码
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream myfile;
myfile.open("test.txt");
char words[10001] = {'\0'}; //c-style string
if (myfile.is_open())
{
while (!myfile.eof())
{
myfile >> words; //read myfile text into char words[]
ofstream outfile;
outfile.open("output.txt"); //ofstream to output.txt based on character in words[]
for (char c : words) //the ofstream to output.txt based on char c in words
{
if (c == '0')
outfile << "---#";
else if (c == '2')
outfile << "--#-";
else if (c == '3')
outfile << "--##";
else if (c == '4')
outfile << "-#--";
else if (c == '5')
outfile << "-#-#";
else if (c == '6')
outfile << "-##-";
else if (c == '7')
outfile << "-###";
else if (c == '8')
outfile << "#---";
else if (c == '9')
outfile << "#--#";
else if (c == 'a')
outfile << "#-#-";
else if (c == 'b')
outfile << "#-##";
else if (c == 'c')
outfile << "##--";
else if (c == 'd')
outfile << "##-#";
else if (c == 'e')
outfile << "###-";
else if (c == 'f')
outfile << "####";
}
}
myfile.close();
}
return 0;
}
我怀疑它是myfile >> words
,但我不完全确定。我添加了一些评论来尝试解释我去的路线。
解决方案
你用过
ofstream outfile;
outfile.open("output.txt");
循环内。这使得文件在每次迭代中打开,这将清除文件的内容。您应该在while
循环之前移动它。
还要注意你的条件while (!myfile.eof())
是错误的。取而代之的是,您应该myfile >> words
在使用“读取”之前将读取移动到条件以检查读取是否成功。
推荐阅读
- php - 我尝试在本地将“srmklive/paypal”:“〜1.0”实施到我的laravel项目中,在测试实施时,我在下面遇到错误
- azure-devops - 更改 Azure DevOps url 是否会影响 Slack 的 Azure DevOps 扩展?
- python - 在 Pipeline 中的特定列上使用 StandardScaler 并连接到原始数据
- javascript - Paper.js - 如何设置绘制矢量或线段的持续时间?
- c# - 如何解决 KeyPress 退格问题
- android - AutocompleteTextView 的自定义 onItemClickListener
- pandas - 在熊猫中计算每个名称和轮次的滞后平均值
- opengl - 从 UE4 坐标更改/转换为 OpenGL 坐标
- reactjs - 如何使用样式化组件覆盖第三方默认样式
- ansible - 设置事实后创建一个新列表