c ++使用指针读入struct数据(歌曲播放列表程序)

时间:2012-02-28 21:13:07

标签: c++ pointers multidimensional-array struct

我有一个类似于IPOD播放列表的项目。我无法在不使用向量的情况下在结构数组中读取数据。我的BF说我的教授错了让我们不使用向量,但这是规则。你们有什么建议吗?我的代码在下面..我的教授说我很接近,但仍然没有编译?感谢您的帮助:))

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;
}

2 个答案:

答案 0 :(得分:0)

也许他想让你使用队列代替?由于歌曲可以在播放列表中“排队”,这可能是一个更合适的数据结构?

答案 1 :(得分: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;
}