c++ - C++ 中具有十六进制值的数组

标签 c++ arrays hex

在最后一天,我在使用这段代码时遇到了一些问题。这里我想用 .txt 上传几个十六进制值,如果前五个数字的总和等于最后一个数字,代码是正确的。然后,方法 main 必须检查其余方法是否成功。但我不知道该怎么做,所以我需要你的帮助...

#include <iostream>
#include <fstream>

#define FILECODE  "file.txt"
#define N_CODE 6

using namespace std;

ifstream file;

void uploadCode(bool& exist, unsigned int longCode, unsigned int code[]);
bool IsValidCode(unsigned int code[]);

void main() {
    unsigned int code[N_CODE];
    bool exist;
    unsigned int longCode=N_CODE;
    IsValidCode(code);
    if(IsValidCode(code)==true){
        uploadCode(exist,longCode,code); //here I have the problem because I don't know how to call the method
        cout << "SUCCESS" << endl;
    }
    else
        cout << "FAIL" << endl;

}

void uploadCode(bool& exist, unsigned int longCode, unsigned int code[]) {
    int i;
    file.open(FILECODE);
    if(file){
        exist=true;
        for(int i=0;i<longCode;i++){
            file >> hex >> code[i];
            cout << "Number " << i << ":  "<< code[i] << endl;
        }

        cout << "EXIST" << endl;
    }
    else
        cout << "NO EXIST" << endl;
        exist=false;
    file.close();

}

bool IsValidCode(unsigned int code[]) {
    int i;
    int sum=0;
    for(int i=0; i<N_CODE-1; i++)
        sum+=code[i];
        cout << "Sum first five numbers:  " << sum << endl;
    if(sum==code[6])
        return true;
    else
        return false;
    return sum;
}

最佳答案

这是一个最小修改的版本,可以满足您的需求。当然,应该对输入处理的返回值进行更好的检查(即 - file >> hex >> code[i];)以查看这些输入是否真的成功。

bool uploadCode(unsigned int longCode, unsigned int code[]) 
{
    bool ret;

    file.open(FILECODE);  // TODO: no need for a global here; just use a locally constructed ifstream

    if (file.good())
    {
        ret = true;

        for(int i = 0; i < longCode; ++i)
        {
            file >> hex >> code[i];
            cout << "Number " << i << ":  "<< code[i] << endl;
        }

        cout << "EXIST" << endl;
    }
    else
    {
        ret = false;
        cout << "NO EXIST" << endl;
    }

    file.close();

    return ret;
}

int main() 
{
    unsigned int code[N_CODE];

    if (!uploadCode(N_CODE, code))
    {
      cout << "File failure!" << endl;
      return 1;
    }

    if (!IsValidCode(code))
    {
        cout << "Code failure!" << endl;
        return 2;
    }

    cout << "SUCCESS" << endl;

    return 0;
}

关于c++ - C++ 中具有十六进制值的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29173806/

相关文章:

arrays - 在go中解码嵌套的json对象

python - 将大型 numpy 数组拆分为训练和测试的内存有效方法

ruby - 如何使用 gsub 将字符串中的所有数字转换为十六进制?

c# - 将嵌套结构从 C# 编码到 C++

c++ - 这个反向字符串代码是否正确?

java - C++ 中的 HashCodeBuilder

perl - 将字符串 "0x30"和十六进制数 0x30 传递给 hex() 函数之间的区别

c++ - 为什么在使用 ostream operator<< 打印字符串时,空格不作为分隔符?

C++。将符号行读入字符数组/vector 的最快方法

c - 标准输入:十六进制值根据标准输入而变化