我正在尝试读取一个文本文件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] = {' '}; //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
移动到检查读取是否成功的条件,然后再使用";读取";。
我建议使用这种方法来处理文件:
ifstream infile("infile.txt");
ofstream outfile("outfile.txt");
if(infile.is_open()){
while(!infile.eof()){
//do the readings
}
}else
{
cout << "ERROR::FILE NOT SUCCESFULLY OPENED";
}