2013-11-23 192 views
0

我試圖通過C++編輯文本文件中的特定值。我的方法是將所有文本值複製到一個數組編輯我想要的然後覆蓋舊文件。一切順利,直到:編輯文本C++中的文件

int nm=0; 
while (nm < arraysize) {    
    myfile << array1[nm]; 
    nm++; 
} 

該文件不會更改或添加新的值。這是全功能

void receptionist::edit_room(int pre1) { 
    fstream myfile ("booked.txt"); 
    int newroom_num; 
    cout << "Please Enter The New Room Number You wish : " << endl; 
    cin >> newroom_num; 
    const int arraysize=20; 
    int array1[arraysize]; 
    int i=0; 
    if(myfile.is_open()) { 
    while(i < arraysize && myfile >> array1[i]) { 
     myfile >> array1[i]; 
     i++; 
    } 
    myfile.clear(); 
    int x=0; 
    while (x < arraysize) { 
     if (pre1 == array1[x]) { 
     array1[x] = newroom_num; 
     break; 
     } 
     x++; 
    }   
    int nm=0; 
    while (nm < arraysize) { 
     if (array1[nm]> -1) { // this is how i fixed the garbage values 
     myfile << array1[nm] << endl; 
     nm++; 
     } 
     else { 
     break; 
     } 
    }   
    myfile.close();   
    } 
    else { 
    cout << "Couldn't Open " << endl ; 
    } 
}; 
+0

,使其更容易閱讀,請格式化代碼 - 沒有人喜歡通過格式化代碼來讀取。 – Rndm

+0

很抱歉,但我不知道如何? – BishoyM

回答

0

點1:

while(!myfile.eof()) 
{ 
    myfile >> array1[i]; 
    i++; 
} 

更好的方法是:

while(i < arraysize && myfile >> array1[i]) 
{ 
    i++; 
} 

點2:

while (x<= arraysize){ 

<=更改爲<,因爲array1[arraysize]超出了界限。

3點:

而且IMO你應該在寫入文件中刪除此檢查。

while (array1[nm]!= EOF){ // remove it. 

相反:

while (nm < arraysize) { // not <= 
myfile << array1[nm]; 
nm++; 
} 
+0

我會試一試thx – BishoyM

+0

對不起,但它仍然是相同的,我改成你的一樣 – BishoyM

+0

@BishoyM嘗試清除錯誤標誌後,通過myfile.clear()讀取文件; –