ASCII到二进制转换,逐行读取c ++

时间:2018-04-10 10:45:45

标签: c++ binary ascii converter

我试图将" ASCII调整为二进制"解决方案found here,我的任务。

此解决方案读取用户输入的行。 对我来说,我希望逐行读取文件并将每一行分配给此解决方案,以便将其转换,然后写入二进制输出文件。

代码工作正常,但是当我打开二进制文件时,我发现只转换了第一行。 任何想法?

感谢您的时间。

#include <iostream>
#include <stdlib.h>
#include <iomanip>
#include <math.h>
#include <fstream>
#include <string.h>

int main(int argc, char const *argv[])
{

    int digit[1000], len, base(2), rem[8], j(0), k(8);
    std::string ch;

std::ofstream writeFile;
    if (argv[1])
    {

    std::ifstream infile(argv[1]);
    std::cout << "good \n";

    std::cout<<"\nASCII(STRING): ";

while (!infile.eof())
{
    std::getline(infile, ch);

    //calc the length of ch
    len = ch.length();
    std::cout << len <<"\n";

    for(int i=0; i<len; i++){
        digit[i] = static_cast<int>(ch[i]);
    }

    //file stream section begins here
    // std::ofstream writeFile;
    writeFile.open("ASCII-BINARY.bin");

   // std::cout<<"BINARY: ";
    for(int m=0; m<len; m++){
        while(digit[m]>0||j<8){
            //finds the remainder of the number
                rem[j] = digit[m]%base;
            //divides the number by the base value choosed
                digit[m] = digit[m]/base;
            //increments the array value
                j++;
            }

        while(k>0){
                //outputs the binaries
                std::cout<<rem[k-1];
                writeFile<<rem[k-1];
                //decrements the array value
                k--;
            }
        std::cout<<" "; //output the space after binary value here
        writeFile<<" ";
        //std::cout<<"\n"; 
        //resets the iterators
        j = 0;
        k = 8;

    }


}
 writeFile.close();
    //file stream section ends here
std::cout << "good close \n";

    }
    else std::cerr << "can't open file ! \n" ; 

    return 0;
}

0 个答案:

没有答案