2017-03-12 15 views
-1

숫자를 10 진수에서 2 진수로 변환하는 프로그램을 작성 중입니다. 나는 이미 그것을위한 알고리즘을 가지고 있고 프로그램은 괜찮아요 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()); 
} 
+4

'remainder [remainder_count]'-'remainder_count == 15 '인 경우 어떻게됩니까? 그 라인에 뭐가 잘못 보이니? – PaulMcKenzie

+1

스택 오버플로에 오신 것을 환영합니다. [The Tour] (http://stackoverflow.com/tour)를 읽으신 후 [Help Center] (http://stackoverflow.com/help/asking)의 자료를 참조하십시오. 여기에 물어보십시오. –

+1

이러한 문제를 해결하는 올바른 도구는 디버거입니다. 스택 오버플로를 묻기 전에 코드를 단계별로 실행해야합니다. 자세한 도움말은 [작은 프로그램 디버깅 방법 (Eric Lippert 작성)] (https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)을 참조하십시오. 문제를 재현하는 [최소, 완료 및 확인 가능] (http://stackoverflow.com/help/mcve) 예제와 함께 해당 질문을 \ [편집]해야합니다. 디버거. –

답변

1

프로그램이 보증되지 행동 : 여기 내 소스 코드입니다. 동작이 정의되지 않았으므로이 문제는 파일 스트림을 사용하는 것과는 반대로 std::cout을 사용하는 것과 아무런 관련이 없습니다.

int remainder [15] = {0}; 
//... 
remainder_count = 15; 
//... 
remainder[remainder_count] = num % 2; // out-of-bounds access (remainder[15] is out-of-bounds) 

위의 행이 실행되면 프로그램이 어떻게 작동할지에 대한 모든 배팅이 해제됩니다. 배열의 유효한 색인 범위는 0에서 n-1까지이며, 여기서 n은 배열의 요소 수입니다. 유효한 유효 색인은 remainder 배열의 경우 0, 1, 2, 최대 14입니다.

는 대신 정의되지 않은 동작, 당신은 당신이 at()을 사용하여 해당 요소에 액세스하는 즉시 던져진 std::out_of_range 예외를 얻을 것 대신 일반 C++ 배열의 std::array를 사용으로 전환 한 경우. 당신이 볼 당신이있어서

 std::array<int, 15> remainder= {{0}}; 
    remainder_count = 15; 
    //...  
    if (num > 0 && num <= 65535) 
    { 
     while (num > 0) 
     { 
      remainder.at(remainder_count) = num % 2; //... exception thrown 

Live Example

그래서, 프로그램은 "잘 실행하지"결코, 당신이 범위를 벗어날 배열의 예정되지 않도록 당신은 당신의 프로그램을 수정해야합니다 .

+0

어레이의 팁 주셔서 감사합니다. 나는 그것을 잘못 사용하고 있다는 것을 몰랐다. 배열을 만들었을 때 숫자는 0에서 시작하여 15로 끝나는 요소가 몇 개가 될 것이라고 생각했습니다. 어떤 식으로 16 개가 될 것입니다. 배열을이 고정 값으로 변경하면됩니다. 배열 나머지; –