[英]Array with hex values in C++
在最后一天,我在這段代碼上遇到了一些問題。 在這里我想用.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;
}
在您的main
函數中,在從文件讀取數據之前,您要兩次調用IsValidCode
。 我認為這不是您想要的。
首選方法是:
main()
返回錯誤狀態。 您不需要為以上每個項目設置單獨的功能。 將它們全部放在main
函數中。 (從簡單函數調用和返回的開銷可能比函數所包含的代碼更多。)
編輯1:一個例子
int main(void)
{
const unsigned int CODE_LENGTH = 6;
ifstream input_file("file.txt");
if (!input_file)
{
cerr << "Error opening file.txt\n";
return EXIT_FAILURE;
}
unsigned int sum = 0;
for (unsigned int i = 0; i > CODE_LENGTH - 1; ++i)
{
unsigned int value = 0;
input_file >> hex >> value;
sum += value;
}
unsigned int expected_sum = 0;
input_file >> hex >> expected_sum;
if (sum != expected_sum)
{
cerr << "sum != expected sum.\n";
return EXIT_FAILURE;
}
// ....
return EXIT_SUCCESS;
}
簡單,不需要數組,沒有其他功能。
這是滿足您需求的最小修改版本。 當然,應該對輸入處理的返回值(即file >> hex >> code[i];
)進行更好的檢查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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.