我正在編寫一個程序來將數字從十進制轉換爲二進制。我已經有了正確的算法,並且使用cout時程序工作正常。但是,只要我在循環中使用outfile,程序就會崩潰,出現錯誤代碼(0xC0000005)。 這裏是我的源代碼:Outfile導致內存衝突崩潰
通過訪問一個元素外的界限#include <iostream>
#include <iomanip>
#include <fstream>
#include <cmath>
using namespace std;
int main()
{
int num, remainder_count;
ifstream infile; //define new input file stream
ofstream outfile; //define new output file stream
infile.open("C:\\Users\\Arctic-Gaming\\CLionProjects\\working\\Source\\Binary Conversion (Loop w File)\\Binary Input.txt"); //connect the stream to an actual file
if (!infile)
{
cout << "Cannot open input file! Program aborted" << endl;
return 1;
}
outfile.open("C:\\Users\\Arctic-Gaming\\CLionProjects\\working\\Source\\Binary Conversion (Loop w File)\\Decimal Output.txt"); //connect the stream to an actual file
do
{
int remainder [15] = {0};
remainder_count = 15;
infile >> num;
outfile << "\n" << num << endl;
if (num > 0 && num <= 65535)
{
while (num > 0)
{
remainder[remainder_count] = num % 2;
num /= 2;
remainder_count--;
}
remainder_count = 0;
while (remainder_count < 16)
{
if (remainder_count % 4 == 0)
{
outfile << " ";
}
outfile << remainder[remainder_count];
remainder_count++;
}
}
else if (num == 0)
outfile << "0000 0000 0000 0000" << endl;
else
cout << "Error! Invalid Input." << endl;
}
while (!infile.eof());
}
'remaining [remainder_count]' - 如果'remaining_count == 15'怎麼辦?看到那條線有什麼問題? – PaulMcKenzie
歡迎使用堆棧溢出。請花些時間閱讀[The Tour](http://stackoverflow.com/tour),並參閱[幫助中心](http://stackoverflow.com/help/asking)中的資料,瞭解您可以在這裏問。 –
解決這些問題的正確工具是您的調試器。在*堆棧溢出問題之前,您應該逐行執行您的代碼。如需更多幫助,請閱讀[如何調試小程序(由Eric Lippert撰寫)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,您應該\編輯您的問題,以包含一個[最小,完整和可驗證](http://stackoverflow.com/help/mcve)示例,該示例再現了您的問題,以及您在調試器。 –