【发布时间】:2015-05-24 07:00:18
【问题描述】:
在最后一天,我在使用此代码时遇到了一些问题。这里我想用一个.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在标准库中使用。 -
In
IsValidCode()return sum;永远不会被执行。 -
@chris 这是一个很好的例子来说明为什么不用不必要地使用宏我读了 3 遍才明白你的意思
-
什么是
IsValid(code);?此外,您正在一个未初始化的数组上调用IsValidCode(code);——因此该函数只是检查堆栈上发生的任何垃圾。这是你的意图吗? -
@chris 抱歉,那是因为这段代码的某些单词是西班牙语,我翻译了它们,例如“文件”。我已经改过了。