c++ - 将文件中的数字合并为一个
问题描述
我有一个任务,我要提供一个包含数字的文件:
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 + 0
which 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;
}
当我运行我的程序时,我得到了这个
解决方案
#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;
}
推荐阅读
- java - JNDI 环境中定义的名称为“java:/TDS”的无效 bean 定义
- c# - 试图将值添加到复选框中
- axios - 路线帖子在laravel 7上没有响应
- python - pyinstaller 在隐藏导入中添加嵌套模块不起作用
- reactjs - 错误:错误:无法从 `node_modules/react-native-pie/src/Pie.js` 解析模块`@react-native-community/art`
- python - 当我运行 Pygame 时,它什么也没做
- javascript - 将部分 JSON 对象合并到一个数组中
- php - get_avatar wordpress 图像从不显示但出现在控制台中
- c# - 匹配列表与列表
- python - How to upsert pandas DataFrame to PostgreSQL table?