2012-04-06 70 views
0

我有一個問題,我基本上感到困惑。首先,我有兩個全局數組 - trustArray []和fashionArray []。下面是填充trustArray功能:atof改變全局數組值

void getTrust() 
{ 
    string line; 
    int reachedTrust=0; 
    int numberOfTrustsRecorded=0; 
    ifstream myfile ("BuyingJeans.Hw5 (1).csv"); 
    if (myfile.is_open()) 
    { 
     while (myfile.good()) 
     { 
      getline (myfile,line,','); 
      //int found=line.find("Like-Purchase"); 
      if (line=="Trust-Like"){ 
       reachedTrust=1; 
       getline (myfile,line,','); 
      } 
      if(reachedTrust==1){ 
       if(numberOfTrustsRecorded <6){ 
        double testValue = atof(line.c_str()); 
        trustArray[numberOfTrustsRecorded] = testValue; 
        numberOfTrustsRecorded++; 
       } 
      } 
     } 
     myfile.close(); 
    } 
    else 
     cout << "Unable to open file"; 
} 

出於某種原因,在此功能的atof()正在改變兩個fashionArray []中的值的。如果我將atof()改爲atoi(),則問題不再發生。下面是填充正在更改陣列(fashionArray [])的方法:

void getFashion(){ 
string line; 
int reachedFashion=0; 
int numberOfFashionsRecorded=0; 
ifstream myfile ("BuyingJeans.Hw5 (1).csv"); 
if (myfile.is_open()) 
{ 
    while (myfile.good()) 
    { 
     getline (myfile,line,','); 
     if (line=="Like-Fash -->"){ 
      reachedFashion=1; 
      getline (myfile,line,','); 
      //cout<<line<<endl; 
      //getchar(); 
     } 
     if(reachedFashion==1){ 
      if(numberOfFashionsRecorded <6){ 
       fashionArray[numberOfFashionsRecorded] = atoi(line.c_str()); 
       numberOfFashionsRecorded++; 
      } 
     } 

    } 
    myfile.close(); 
} 

else cout << "Unable to open file"; 

}

這裏是調用這兩種方法的主要方法:

int main() { 

getFashion(); 
getTrust(); 

for(int x=0; x<6;x++) 
    cout<<fashionArray[x]<<endl; 
getchar(); 
return 0; 
} 

第一fashionArray的兩個值最終變成了一些荒謬的大負值和正值。一個有趣的事情是,如果我顛倒main()方法中調用這兩個方法的順序,則問題不再發生。任何人都有任何想法可能會造成這種情況?

+5

trustArray聲明和分配在哪裏? – DRVic 2012-04-06 01:37:17

+0

可怕的大負值和正值聽起來就像'atof()'無法轉換C字符串(值超出範圍,因此+/- HUGE_VAL被返回)... – user268396 2012-04-06 01:46:49

+0

trustArray是全局聲明和分配的,與數組相同正在改變。我同意超出範圍的解釋,但我仍然困惑,爲什麼這會導致不同數組的值被更改。 – 2012-04-06 02:39:32

回答

2

我認爲你的寫作超出了trustArrayfashionArray。您沒有提供初始化代碼(請這麼做),但我想它看起來是這樣的:

float trustArray[N]; 
float fashionArray[N]; 

n等於給一些正整數。我的猜測是,在你的情況下,N=5

在你的循環中,你測試的是numberOfTrustsRecorded < 6。將通過該測試的numberOfTrustsRecorded的值分別爲0,1,2,3,4,5。這是六(6)個浮點數以適合5的數組。寫入numberOfTrustRecorded[5]將覆蓋內存。更改您的測試或將緩衝區大小增加到6.

爲什麼在fashionArray [0]中看不到有效值?我不知道。也許你的編譯器將fashionArray內存緩衝區對齊,以便在未使用的內存中開始覆蓋,留下一半的位來製作IEEE浮點數。內存中的任何位都構成隨機浮點數。內存轉儲會顯示問題。

爲什麼按相反的順序運行該方法?可能該錯誤仍然存​​在,但運行getFashion()秒會清除getTrust()留下的混亂。你覆蓋的記憶是你的,所以只要你不想理解它,沒有人抱怨。在運行getFashion()之前初始化fashionArray[0] = 0.0,運行getTrust()並查看fashionArray[0]。你可能會看到隨機的花車。

+0

好人。新手的錯誤 - 我有一個5號陣列,而不是6號陣列。 – 2012-04-06 14:56:38