2015-04-02 28 views
-3

我是新來使用C + +和Microsoft Visual Studio,我試圖將一個數據文件(由浮點數組成的500列2列)轉換爲數組,然後我試圖在屏幕上輸出數組。每當我嘗試運行它時,它都會出現「file.exe中0x001BC864未處理的異常:0xC0000005:訪問衝突寫入位置0x00320A20」。
我發現這個視頻,並試圖改編該代碼https://www.youtube.com/watch?v=4nz6rPzVm70 任何幫助,將不勝感激。在C++教程程序崩潰(閱讀矩陣)

#include<stdio.h> 
#include<string> 
#include<iostream> // 
#include<fstream> // 
#include<array> // 
#include<iomanip> // 
#include<sstream>// 
#include<conio.h> 
using namespace std; 

int rowA = 0; // 
int colA = 0; 


int main() 
{ 
string lineA; 
int x; 
float arrayA[2][500] = { { 0 } }; 
ifstream myfile("C:/results.dat"); 
if (myfile.fail()) { 
    cerr << "File you are trying to access cannot be found or opened"; 
    exit(1); 
} 

    while (myfile.good()) { 
    while (getline(myfile, lineA)) { 
     istringstream streamA(lineA); 
     colA = 0; 
     while (streamA >> x) { 
      arrayA[rowA][colA] = x; 
      colA++;    } 
     rowA++;   } 
} 


cout << "# of Rows --->" << rowA << endl; 
cout << "# of Columns --->" << colA << endl; 
cout << " " << endl; 
for (int i = 0; i < rowA; i++) { 
    for (int j = 0; j < colA; j++) { 
     cout << left << setw(6) << arrayA[i][j] << " "; 
    } 
    cout << endl; 
} 

return 0; 
_getch(); 
} 
+0

如果你有500行兩個浮點數,那麼'float arrayA [2] [500]'和'arrayA [rowA] [colA]'不能很好地結合在一起。如果你有兩條500浮標,他們會。 – Wintermute 2015-04-02 15:04:16

+0

好的,謝謝你,你有什麼我可以做的建議嗎? – Student201 2015-04-02 15:06:29

+3

這個問題不是特定於Visual Studio的。這是一個通用的C++問題。你在使用C++數組時遇到了問題。掌握編程的第一步是能夠確定問題的根源。 – BitTickler 2015-04-02 15:09:24

回答

2

顯然你對數組訪問越界,你有你的數組索引超出數組維度的大小。

鑑於這不會是最後一次遇到此類問題,我的答案會爲您提供有關如何檢測此類錯誤的提示。

您機架上的第一個工具是向您的代碼添加斷言,這會使代碼的調試版本中出現問題。

#include <cassert> 

// ... 
while (myfile.good()) { 
while (getline(myfile, lineA)) { 
    istringstream streamA(lineA); 
    colA = 0; 
    while (streamA >> x) { 
     // probably you would have noticed the error below while writing 
     // those assertions as obviously you would notice that you want 500 
     // rows and not 2 and you want 2 columns, not 500... 
     assert(rowA < 2); // <<--- This will assert! 
     assert(colA < 500); // <<--- This will assert if there are more than 500 lines in the file. 
     arrayA[rowA][colA] = x; 
     colA++;    } 
    rowA++;   } 

由於只有2條額外的線路(和包括),你就已經能夠看到你的代碼攪亂。

在這種情況下,固定你的代碼是很容易的,我把它留給你作爲練習;)

爲了避免混淆爲您的多維數組的索引,你可以寫你的代碼更具提示性的方式(更具可讀性)。

int main() 
{ 
    string lineA; 
    int x; 
    const int NUM_COLUMNS = 2; 
    const int NUM_ROWS = 500; 
    float arrayA[NUM_COLUMNS][NUM_ROWS] = { { 0 } }; 
    // ... 

額外表現的這麼一點點增加你的勝算注意到,您的數組訪問進一步低於使用每個數組維錯誤的指標變量。

最後同樣重要的是,如果輸入文件沒有違反您的假設(2列,少於501行),您應該添加額外的檢查,因爲您的程序只能正確工作(修復後)。這屬於「防禦性編程」一章 - 即您的代碼可以保護自己免於違反控制範圍之外的假設。

你在底部的打印循環中重複你的錯誤,順便說一句。在那裏,你也可以添加斷言。

+0

謝謝,它現在工作! – Student201 2015-04-02 18:29:56