2012-02-28 55 views
0

我有一个项目就像一个IPOD播放列表。我无法读取我的数据,而不使用向量的结构数组中的数据。我的BF说我的教授是错误的让我们不使用矢量,但这是规则。你们有什么建议吗?我的代码在下面..我的教授说我很接近但仍然没有编译?感谢您的任何帮助:)C++使用指针读取结构数据(歌曲播放列表程序)

Struct Songs{ 
string title;  
string artist; 
int mem;   //size of file in MBs 
}song[20];  //up to 20 possible songs 

int main 
{ 
    song * pointer = new song; 
    int num = 0; 

    ifstream fin; 
    fin.open("input.txt") 

    while (fin.good()) 
    { 
    getline(fin, *pointer[num].title; 

    if (*pointer[num].title.empty()) //to skip blank lines 
    continue; 

    getline(fin, *pointer[num].artist; 
    fin >> *pointer[num].mem.get(); //get to avoid whitespace/enter 

    num++; 
    } 

    for (int i = 0; i<num;i++) // my test to see if it reads in properly 
    { 
    cout << *pointer[num].title << endl;  
    cout << *pointer[num].artist << endl; 
    cout << *pointer[num].mem << endl; 
    } 
    fin.close(); 

    delete pointer [] ; 

    return 0; 
} 
+0

编译错误很好显示。无论如何,从看它,你试图指向“歌曲”,而不是“歌曲”。第一行的语法应该是'Songs * pointer = new Songs;'为一个动态创建的新对象或'Songs * pointer = song;'指向预制对象的指针。另外,在删除指针时,只需要一个指向内存位置的指针,就像在'int * intPtr =&somePreviousVariable;'中那样,使用'delete'。对于包含'new'创建的数组的指针,如'int * intPtr = new int [20];',使用'delete []'。在你的情况下,'pointer'指向一个预制数组。 – chris 2012-02-28 21:18:11

+0

谢谢我会改变这个 – gamergirl22 2012-02-28 21:20:42

+1

你的代码充满了简单的错误。你需要使用编译器非常有用的错误来修复它们。我们不是来为你做功课的。 – spencercw 2012-02-28 21:21:40

回答

0

也许他希望你使用一个队列,而不是?由于歌曲可能会在播放列表中“排队”,可能是更适合的数据结构?

+5

不是一个真正的答案 - 应该只是一个评论 – 2012-02-28 21:20:58

0

我可能错过了一些,但我相信我标记了我为解决此问题所做的所有更改。很多语法错误,我放在//旁边。另外主要是我改变了分配给新的歌曲[20],所以你为20首新歌分配足够的空间。

#include <iostream> 
#include <fstream> 
using namespace std; 

struct Songs{ // Fixed - You had an uppercase S on 'struct' 
    string title;  
    string artist; 
    int mem;   //size of file in MBs 
}; // fixed - Removed since we will be allocating in Main() 

int main() // fixed - you are missing() at the end of main 
{ 

    Songs * pointer = new Songs[20]; //up to 20 possible songs // Fixed - You allocate 20 new Songs here 
    int num = 0; 

    ifstream fin; 
    fin.open("input.txt"); 

    while (fin.good()) 
    { 
      // Fixed - all uses of pointer as an array don't need to be de-referenced with *, [num] will do it 
     getline(fin, pointer[num].title); // Fixed - you were missing the functions closing) 

     if (pointer[num].title.empty()) //to skip blank lines 
      continue; 

     getline(fin, pointer[num].artist); // Fixed - you were missing the functions closing) 
     fin >> pointer[num].mem; //get to avoid whitespace/enter // Fixed - removed .get() 

     num++; 
    } 

    for (int i = 0; i<num;i++) // my test to see if it reads in properly 
    { 
     cout << pointer[num].title << endl;  
     cout << pointer[num].artist << endl; 
     cout << pointer[num].mem << endl; 
    } 
    fin.close(); 

    delete [] pointer; 

    return 0; 
}