首页 > 解决方案 > 将文件中的数字合并为一个

问题描述

我有一个任务,我要提供一个包含数字的文件:

5  1 0 1 1 0
4  1 1 9 0 
7  1 1 1 0 1 0 1
10 1 0 1 1 1 0 0 0 1 0

第一个数字(5、4、7 和 10)用来说明二进制数应该有多少位数。然后必须组合之后的数字,因为它们之间有空格。

我知道如果他们没有空格但作业需要空格会更好。

我的代码采用我命名的第一个数字,numLength然后计算出二进制值应该有多少位。然后它一次输入每个数字并将其提高到适当的幂,以便理论上当它们全部相加时,它应该等于二进制数。

例如1 0 1 1 0变成10000 + 0 + 100 + 10 + 0which equals10110

这应该发生,因为文件上有一个二进制值。

当我运行我的程序时,它不会输出它应该输出的内容。

关于如何改进我的代码以使其做我想做的事情的任何建议?

#include <iostream> // This library is the basic in/out library
#include <cmath> //This library allows us to use mathematical commands
#include <fstream> //This library will allow me to use files
#include <string> //This will allow me to use strings

using namespace std;
int convertBinaryToDecimal(int);

int combine(int);

int main()
{
    ifstream infile; //I am renaming the ifstream command to infile since it is easier to remember and us
    ofstream outfile; //I also renamed the ofstream to outfile

    infile.open("binary.txt"); //This is opening the binary.txt file which has to be located on the master directory
    int numLength; //This will determine how many digits the binary number will have
    infile >> numLength;
    int digits, binary = 0, DECIMAL;
    int counter = numLength - 1;
    while (!infile.eof())
    {
        infile >> digits;
        for (int i = 0; i < numLength; i++)
        {
            binary = binary + (pow(10, counter) * digits);
            counter = counter - 1;
            infile >> digits;
        }
        cout << binary << endl;
        //DECIMAL = convertBinaryToDecimal(digits);
        //cout << DECIMAL;
        infile >> numLength;
    }

    return 0;
}

当我运行我的程序时,我得到了这个

图片

标签: c++

解决方案


#include <iostream> // This library is the basic in/out library
#include <fstream> //This library will allow me to use files
#include <string> //This will allow me to use strings
#include <sstream>

using namespace std;

int main()
{
    ifstream infile; //I am renaming the ifstream command to infile since it is easier to remember and us
    ofstream outfile; //I also renamed the ofstream to outfile

    infile.open("binary.txt"); //This is opening the binary.txt file which has to be located on the master directory
    int numLength; //This will determine how many digits the binary number will have

    string line;
    while (getline(infile, line))
    {
        istringstream iss(line);
        iss >> numLength;

        int digit, binary = 0;

        for (int i = 0; i < numLength; i++)
        {
            iss >> digit;
            if (digit == 1)
                binary |= (numLength - i - 1));
        }

        cout << binary << endl;
    }

    return 0;
}

现场演示


推荐阅读