首页 > 解决方案 > 使用 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,但我不完全确定。我添加了一些评论来尝试解释我去的路线。

标签: c++iostream

解决方案


你用过

            ofstream outfile;
            outfile.open("output.txt");

循环内。这使得文件在每次迭代中打开,这将清除文件的内容。您应该在while循环之前移动它。

还要注意你的条件while (!myfile.eof())错误的。取而代之的是,您应该myfile >> words在使用“读取”之前将读取移动到条件以检查读取是否成功。


推荐阅读