2015-10-12 3 views
-1

У меня возникла небольшая проблема, когда дело доходит до этого простого приложения для сортировки музыки, которое я пытаюсь создать. Я борюсь с ним на некоторое время и пробую разные вещи, но независимо от того, что я продолжаю получать от сегментации.Ошибка сегментации при попытке открыть входной файл в массив

#include <iostream>     
#include <string>  
#include <cctype> 
#include <iomanip> 
#include <fstream> 

using namespace std; 

//Constants 
const int MAX_CHAR = 101; 
const int SONG_CAPACITY = 100; 

struct song { 
char title[MAX_CHAR]; 
char artist[MAX_CHAR]; 
char album[MAX_CHAR]; 
char duration[MAX_CHAR]; 
}; 

//Function Prototypes 
void dispLibrary(song library[], int& index); 
void loadLibrary(const char fileName[], song library[], int& index); 
void addEntry(const char fileName[], song library[], int& index); 

int main(){ 
int command; 
song library[SONG_CAPACITY]; 
int index = 0; 
char fileName[] = "songs.txt"; 

loadLibrary(fileName, library, index); 
while(command != 5){ 
    cout << "Please select an action (1-5): "; 
    cin >> command; 
    switch(command){ 
     case 1: 
      dispLibrary(library, index); 
      break; 
     case 2: 
      break; 
     case 3: 
      break; 
     case 4: 
      break; 
     case 5: 
      break; 
    } 
} 
} 

void addEntry(const song& entry, song library[], int& index) 
{ 
strcpy(library[index].title, entry.title); 
strcpy(library[index].artist, entry.artist); 
strcpy(library[index].album, entry.album); 
strcpy(library[index].duration, entry.duration); 
index++; 
} 

void loadLibrary(const char fileName[], song library[], int& index) 
{ 
ifstream  songFile; 
char   title[MAX_CHAR]; 
char   artist[MAX_CHAR]; 
char   album[MAX_CHAR]; 
char   duration[MAX_CHAR]; 
song   entry; 

songFile.open(fileName); 
if(!songFile) 
{ 
    songFile.clear(); 
    cerr << endl << "Fail to open " << fileName << " for input!" << endl  << endl; 
    //exit(1); 
} 

songFile.get(title, MAX_CHAR, ';'); 
while (!songFile.eof()) 
{ 
    songFile.get();          
    songFile.get(title, MAX_CHAR, ';'); 
    songFile.get(artist, MAX_CHAR, ';'); 
    songFile.get(album, MAX_CHAR, ';'); 
    songFile.get(duration, MAX_CHAR, '\n'); 
    songFile.ignore(100, '\n');    

    strcpy(entry.title, title); 
    strcpy(entry.artist, artist); 
    strcpy(entry.album, album); 
    strcpy(entry.duration, duration); 

    addEntry(entry, library, index); 

    songFile.get(title, MAX_CHAR, ';');  //start the next record 
} 
songFile.close(); 
} 

void dispLibrary(song library[], int& index){ 
int i; 
cout << setw(10) << "Title" << setw(10) << "Artist" << setw(10) << "Album" << setw(10) << "Duration" << endl; 
for(i=0; i<index; i++) 
{ 
    cout << setw(10) << library[i].title << setw(10) << library[i].artist << endl; 
} 
} 

Я действительно хочу знать, почему этот код выходит из строя с ошибкой сегментации, любой ввод приветствуется, спасибо.

+1

Где ошибка сегментации? Какой результат вы получаете, когда он падает? – 1201ProgramAlarm

+0

Вы пробовали пропустить свой код, чтобы узнать, где происходит segfault? Вы должны изучить использование 'std :: strind' вместо строк C – NathanOliver

+0

@ 1201ProgramAlarm В Windows программа просто сбой, но в Linux она просто говорит« Ошибка сегментации ». Это происходит, когда я открываю входной файл, как когда я комментирую из этой строки программа проходит без ошибок. –

ответ

0

Одна из ваших проблем заключается в том, что вы получили название гораздо больше, чем в файле. Предположив файл содержит следующее:

title;artist;album;duration 
title2;artist2;album2;duration 

... Я добавлю некоторые комментарии после каждой строки, которая считывает из файла, чтобы показать, что все еще непрочитанные:

songFile.get(title, MAX_CHAR, ';'); // Read the first title. 

/* artist;album;duration 
* title2;artist2;album2;duration 
*/ 

while (!songFile.eof()) 
{ 
    songFile.get(); // Read the 'a' in "artist".       

/* rtist;album;duration 
* title2;artist2;album2;duration 
*/ 

    songFile.get(title, MAX_CHAR, ';'); // Read "rtist;", overwriting the title var that has already been read. 

/* album;duration 
* title2;artist2;album2;duration 
*/ 

    songFile.get(artist, MAX_CHAR, ';'); // Read "album;" into the artist variable. 

/* duration 
* title2;artist2;album2;duration 
*/ 
    songFile.get(album, MAX_CHAR, ';'); // Read "duration\ntitle2;" into the album variable. 
             // Ignores the newline while it searches for the next semicolon. 

/* artist2;album2;duration 
*/ 
    songFile.get(duration, MAX_CHAR, '\n'); // Read until the second newline. 

/* EOF */ 

    songFile.ignore(100, '\n');  // Read past the EOF. 
             // If there was a third record, this would skip it. 

    strcpy(entry.title, title); 
    strcpy(entry.artist, artist); 
    strcpy(entry.album, album); 
    strcpy(entry.duration, duration); 

    addEntry(entry, library, index); 

    songFile.get(title, MAX_CHAR, ';');  // Read past EOF again. 
              // If there was a fourth record, 
              // this would create the same 
              // problem that was caused by 
              // reading the title before 
              // entering the while loop. 
} 
songFile.close(); 
} 
Смежные вопросы