2
所以我是相當新的編碼和C++。所以......對不起,如果這是值得一些你非常明顯:輸入時,它讀取不匹配/通過第二次(C++)
我有一個很難得到這個代碼讀取存儲在txt文件第二次輸入。它第一次運作。
void readcode(ifstream& infile, int list[], int& length, bool& lenCodeOk)
{
int count;
lenCodeOk = true;
infile >> length; //get the length of the secret code
cout << "Length1 is "<<length<<endl;
if (length > MAX_CODE_SIZE)
{
lenCodeOk = false;
return;
}
//Get the secret code.
for (count = 0; count < length; count++)
{
infile >> list[count];
}
cout<<" Code recorded is: ";
for (count = 0; count < length; count++)
{
cout<<list[count]<<" "<<endl;
}
}
所以在我的txt文件的第一個整數整數序列的長度。這個函數完成它應該做的所有事情。正確讀取長度也會將所有內容存儲在數組中。
但是當我在調用readcode函數後調用下面的compareCode函數時,它會出現一個完全隨機的/不同的長度(我每次調用時都會改變一次)和數組元素。
void compareCode(ifstream& infile, ofstream& outfile, const int list[], int length)
{
int length2;
int digit;
bool codeOk;
int count;
codeOk = true;
infile >> length2;
cout<<"Length2 is "<<length<<endl;
if(length != length)
{
cout<< "The original code and its copy are not of the same length"<<endl;
return;
}
outfile << "Code Digit Code Digit Copy"<<endl;
for (count= 0; count<length; count++)
{
infile >> digit;
outfile<<setw(5)<<list[count]<<setw(17)<<digit;
if (digit != list[count])
{
outfile << " Code digits are not the same"<<endl;
codeOk = false;
}
else
{
outfile<<endl;
}
if (codeOk)
{
outfile<<"Message transmitted OK."<<endl;
}
else
{
outfile<<"Error in transmission. "<<"Retransmit!!"<<endl;
}
}
}
好像我缺少的一個重要信息有關傳遞fstream的變量,如果有人指着我朝着正確的方向我會很感激。
int main()
{
int codeArray[MAX_CODE_SIZE];//Array to store the secret code
int codeLength;// Variable to store the length of the code
int codeLength2;
bool lengthCodeOk;//Variable to indicate if the legth of the secret code is less than or equal to 250
ifstream incode;// Declare ifstream variable
ofstream outcode;//Declare ofstream variable
char inputFile[51];//Variable to store the name of the input file
char outputFile[51]; //Variable to store the name of the output file
cout<<"Enter the input file name: "<<endl;
cin>> inputFile;//makesure it is one word because ci.>>skips white space
cout<<endl;
incode.open(inputFile);
if(!incode)
{
cout<< "Cannot open the input file."<<endl;
return 1;
}
cout<< "Enter the output file name: " ;
cin>> outputFile;//Same deal, one word so cin>> can read
cout<<endl;
outcode.open(outputFile);
readcode(incode,codeArray,codeLength,lengthCodeOk);
if (lengthCodeOk)
{
compareCode(incode,outcode,codeArray,codeLength);
}
else
{
cout<<"Length of the secret code must be <= "<<MAX_CODE_SIZE<<endl;
}
incode.close();
outcode.close();
return 0;
}
你在同一個運行在嘗試兩次讀取文件? – hasan83
@ hasan83肯定。這是我不應該做的嗎? –
不行。你是否第二次定義了新的輸入流? – hasan83