2014-03-25 2 views
1

이 코드에 문제가 있습니다 ..... 읽기 방법이 제대로 작동하지만 내 방향 목록에 새 항목을 추가하고이 항목을 추가 할 때 모든 것이 "충돌"합니다. 항목은 모든 항목에 의존하며 오름차순으로 정렬됩니다. 파일의 항목은 오름차순으로 정렬되어 정렬됩니다. 그것은 완벽하게 작동하지 않지만 나는 심지어 코드를 따르기 위해 종이에 everythink를 그려서 화면에 모든 목록을 인쇄하려고 할 때 목록의 마지막 항목을 잃어버린 이유를 모르겠습니다. 제발, 그 문제를 해결하도록 도와주세요. 아래의 코드는 C 및 C++과 혼합되어 있습니다.List가 목록 C의 마지막 항목을 잃습니다.

// NAME YEAR CAPACITY 

Syrena 1977 650 
Maluch 1999 3800 
Polonez 2004 1774 

.... 그 프로그램에 어떤 문제가 : 여기

#include <iostream> 
#include <stdio.h> 
#include <conio.h> 
#pragma warning(disable:4996) 
using namespace std; 

int howManyRecords = 0; // how many record readed from file 


struct pojazd 
{ 
    char model[40]; // Name of the vechicle 
    int yearOfProduction; // Year of production 
    float engineCapacity; // capacity of the engine 
    struct pojazd *nast; // pointer for the next element 
}; 
struct pojazd* creatingNewItem() // method creating new object of this structure for later adding it to list 
{ 
    struct pojazd *tmpVechicle=NULL; 

    tmpVechicle = (struct pojazd*)malloc(sizeof(struct pojazd)); 

// MODEL, YEAR AND CAPACITY OF THE ENGINE 
///////////////// 
    cout << "Zaraz podasz dane nowego pojazdu. Przygotuj sie." << endl << endl; 
    cout << "Podaj model samochodu: "; cin >> tmpVechicle->model; cout << endl; 
    cout << "Podaj rok produkcji samochodu: "; cin >> tmpVechicle->yearOfProduction; cout << endl; 
    cout << "Podaj pojemnosc silnika samochodu: "; cin >> tmpVechicle->engineCapacity; cout << endl; 

    tmpVechicle->nast = NULL; 

    cout<<"Model:"<< tmpVechicle->model<<" rok:" << tmpVechicle->yearOfProduction << " pojemosc:" << tmpVechicle->engineCapacity <<endl; 

    return tmpVechicle; 

} 


//Adding new created item to the list using pointers to list and new item 
// Adding it to the list keeping ascending politic. 

void addingNewItemToList(struct pojazd *headList, struct pojazd *newItem) 
{ 

    struct pojazd *pomocnicza = NULL, *head = NULL; 

    head = headList->nast; 
    pomocnicza = headList; 

    while(true) 
    { 


      if((pomocnicza->yearOfProduction < newItem->yearOfProduction) && (newItem->yearOfProduction < head->yearOfProduction)) 
      { 
       pomocnicza->nast = newItem; 
       newItem->nast = head; 
       break; 
      } 
      else if((head->nast == NULL) && (pomocnicza->yearOfProduction < newItem->yearOfProduction)) 
      { 
       pomocnicza->nast = newItem; 
       break; 
      } 
      else 
      { 
       pomocnicza = head; 
       head = head->nast; 
      } 
    } 

} 

// READING FROM FILE AND ALLOCATING NEW OBJECT OF LIST 
///////////////////////// 
struct pojazd* uzupelnianieListy(FILE *odczytywanie) 
{ 


    struct pojazd *beggining = NULL,*nextElement = NULL; 

    while (!feof(odczytywanie)) 
    { 
     if (beggining == NULL) 
     { 
      beggining = nextElement = (struct pojazd*)malloc(sizeof(struct pojazd)); 
     } 
     else 
     { 
      nextElement->nast = (struct pojazd*)malloc(sizeof(struct pojazd)); 
      nextElement = nextElement->nast; 
     } 

     fscanf(odczytywanie, "%s %d %f", nextElement->model, &(nextElement->yearOfProduction), &(nextElement->engineCapacity)); 
     cout << nextElement->model << endl; 
     cout << nextElement->yearOfProduction << endl; 
     cout << nextElement->engineCapacity << endl; 

     cout << "\n"; 
     nextElement->nast = NULL; 

     howManyRecords++; 
     cout<< howManyRecords <<endl; 

    } 
    fclose(odczytywanie);//closing pliku 

    system("pause"); 

    return beggining; 

} 


int main() 
{ 
// INPUT OUTPUT FILE 
    char wejscie[20], wyjscie[20]; 

    FILE* odczytywanie; 
    FILE *zapisywanie; 
//HEAD OF THE LIST 
    struct pojazd *headList = NULL; 
//NEW ITEM POINTER 
    struct pojazd *newItem = NULL; 

//ADDITIONAL POINTER IN PRINTING CODE at THE BOTTOM 
    struct pojazd *helper = NULL; 


    cout << "Podaj nazwe pliku do odczytu: "; cin >> wejscie; 
    odczytywanie = fopen(wejscie, "r"); 




    headList = uzupelnianieListy(odczytywanie); 


    newItem = creatingNewItem(); // Creating new Item 

    addingNewItemToList(headList, newItem); 

    helper = headList; 

    /// NEW LIST OF ITEMS 
    //// 
    cout << "*************************Nowa lista*********************" << endl; 
    for(int i = 0; i < howManyRecords; i++) 
    { 

     cout << helper->model << endl; 
     cout << helper->yearOfProduction << endl; 
     cout << helper->engineCapacity << endl; 

     helper = helper->nast; 

    } 
    cout << "*************************koniec Nowa lista*********************" << endl; 


    _getch(); 
    return 0; 
} 

는 내용의 파일입니까?

+0

그냥 폴란드어 식별자 이름을 사용하지 마십시오. 폴란드어가 아닌 사람도 코드를 보지 못하게하는 것이 매우 어렵습니다. – fritzone

+2

이것은 약간 잘난 척 할 지 모르지만, 영어로 코드를 작성하면 도움이 될 가능성이 커집니다. 변수 이름이 나에게 횡설수설하기 때문에 흐름을 따라 가는데 어려움을 겪고 있습니다. 그게 뭐야? 폴란드어? :) –

+0

확실히 재 작성해주세요. – Darek

답변

1

새 레코드를 추가 할 때 ileRekordowdodawanieDoListy에 증가시키지 마십시오. 어떻게해야, 다음

는 예 (또는이 새 코드에서 addingNewItemToListhowManyRecords입니다) : 또한

void addingNewItemToList(struct pojazd **headList, struct pojazd *newItem) 
{ 

    struct pojazd *pomocnicza = NULL, *head = NULL; 

    head = (*headList)->nast; 
    pomocnicza = *headList; 

    while(true) 
    { 


     if(head == NULL) 
     { 
      pomocnicza->nast = newItem; 
      break; 
     }else if((pomocnicza->yearOfProduction <= newItem->yearOfProduction) && (newItem->yearOfProduction < head->yearOfProduction)) 
     { 
      pomocnicza->nast = newItem; 
      newItem->nast = head; 
      break; 
     }else if (pomocnicza->yearOfProduction>newItem->yearOfProduction){ 
      newItem->nast=pomocnicza; 
      (*headList)=newItem; 
      break; 
     } 
     else 
     { 
      pomocnicza = head; 
      head = head->nast; 
     } 
    } 
    howManyRecords++; 

} 

, 나는이 함수의 선언을 변경하기 때문에, 그것은 같이 호출해야 이 :

addingNewItemToList(&headList, newItem); 
+0

나는 그것을 증가시키고 값은 3입니다. – Darek

+0

@Darek, 아니요. 파일에서 레코드를 추가 할 때 - 얼마나 많은 레코드를 증가시키지 만, 키보드 입력에서 새 레코드를 삽입 할 때 - 얼마나 많은 레코드를 증가시키지 않으므로 결과를 출력 할 때리스트의 마지막 레코드는 인쇄하지 않습니다. – Ryzhehvost

+0

대단히 감사합니다. 한 가지와 너무 많은 문제 :) – Darek

0

디버거를 통해 코드를 실행해야합니다. 기회는 포인터와 관련이 있습니다. 예를 들어, 당신은 문제의 원인 정확한 라인을 찾기 위해 매우 쉽게 GDB를 사용할 수 있습니다

GDB your_executable

실행이

역 추적

F0 (또는 다른 번호가 볼을있는 버그의 코드 부분)

그러면 segfault가 발생한 줄을 알려줍니다. -g로 컴파일해야 디버거와 함께 작동 할 수 있습니다.

또한 포인터를 사용해야하는 지 모르겠지만 표준 라이브러리에는 자동 메모리 관리 (std :: vector, std :: list 등)가있는 일부 데이터 구조가 있습니다. 수동 할당 (malloc)을 명시 적으로 사용할 필요가없는 경우 메모리를 직접 관리하려면 1) stl 컨테이너를 사용하고 2) 새 연산자를 사용하는 것이 더 좋습니다.

+0

예 도서관이 있다는 것을 알고 있지만 선생님은 초등 회 구조를 사용하여이 작업을 수행하도록 요청했습니다.- – Darek

관련 문제