2012-12-14 22 views
1
#include <iostream> 
#include <fstream> 
#include <cstring> 

using namespace std; 

void main() 
{ 
    char info[81]; 
    string names[5]; 
    double sales[5][5]; 
    int count = 0; 
    int x = 0; 
    ifstream file; 
    file.open("sales.txt"); 

    while(!file.eof()) 
    { 
     x = 0; 
     file.getline(info, 80); 
     while(info[x] != (char)39) 
     { 
      while(info[x] != ' ') 
      { 
       names[count] += info[x]; 
       x++; 
      } 
      x++; 
      for(int y = 0; y < 4; y++) 
      { 
       sales[count][atoi(&info[x])] = (atoi(&info[x + 1]) * 10) + atoi(&info[x+2]) + (.01 *((atoi(&info[x+4])*10) + atoi(&info[x+5]))); 
       x += 7; 
      } 
      x++; 
     } 
     count++; 
    } 
} 

當我運行這個時出現運行時錯誤,但我無法弄清楚爲什麼。我不是很熟悉我的編譯器調試器,所以我在調試時遇到了麻煩。(while(info [x]!='')時出現訪問衝突錯誤)

+2

什麼恐怖的代碼。你有一個非常好的理由,你爲什麼不能使用'std :: string'和'std :: getline'?沒有人可以真正想要調試*那混亂。 –

+0

如果你說'(char)39',那麼你還應該說'x =(int)0',非? –

回答

4

我會認爲'x'超出了數組(信息)範圍。在再次進入循環之前,您應該檢查x是否小於81。

例:

while(x < 81 && info[x] != (char)39) 
    { 
     while(info[x] != ' ') 
     { 
      names[count] += info[x]; 
      x++; 
     } 
     x++; 
     for(int y = 0; y < 4; y++) 
     { 
      sales[count][atoi(&info[x])] = (atoi(&info[x + 1]) * 10) + atoi(&info[x+2]) + (.01 *((atoi(&info[x+4])*10) + atoi(&info[x+5]))); 
      x += 7; 
     } 
     x++; 
    } 

不管怎樣,同樣可能發生在那些內循環線路。你假設你的輸入將有一定長度的字符串,如果它沒有發生,你會再次得到這個錯誤。


如果你企圖分裂在空間的每一行,你可以考慮使用的格式輸入,而不是(每行):

 stringStream >> names[count]; 
     string theNextString; 
     stringStream >> theNextString; 
     // Process the theNextString, which is the string after the last space (and until the next one) 

而且,這條線是非常容易出錯。我建議你把它分成更小的部分更容易理解(並且更少依賴於線的確切長度)。你甚至可以使用格式化輸入來獲取數字。

sales[count][atoi(&info[x])] = (atoi(&info[x + 1]) * 10) + atoi(&info[x+2]) + (.01 *((atoi(&info[x+4])*10) + atoi(&info[x+5]))); 

使用格式化輸入,它看起來像

int firstNumber; 
stringStream >> firstNumber; 

請注意,上面的,如果你的號碼之間用空格分隔纔會工作。

0

再次檢查後,我推測,它可能是這行代碼的:

sales[count][atoi(&info[x])] = (atoi(&info[x + 1]) * 10) + atoi(&info[x + 2]) + (.01 *((atoi(&info[x + 4]) * 10) + atoi(&info[x + 5]))); 

你絕對的info邊界之外會和步入一些其他的存儲位置。這很可能是導致內存訪問衝突的原因。