将文本文件读入结构数组c ++

时间:2017-04-18 17:37:16

标签: c++ arrays struct char

这是一项家庭作业,但我所呈现的是一个小型测试程序,用于我的作业。

首先,我要在文件" songs.txt"中列出一系列歌曲。我当前的文件看起来像这样。

Maneater;4;32
Whip It;2;41
Wake Me Up Before You Go-Go;3;45

该文件只包含一个歌曲标题,以及以分钟和秒为单位的持续时间,标题,分钟和秒以分号分隔。完整文件应该包含艺术家和专辑,所有都用分号分隔。无论如何,代码。

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

const int CAP = 100;
const int MAXCHAR = 101;

struct songInfo
{
    char title[CAP];
    char durMin[CAP];
    char durSec[CAP];

};

void getData(songInfo Song[], int listSize, int charSize);

int main()
{
    string fileName;
    songInfo Song[CAP];
    ifstream inFile;

    cout << "What is the file location?: ";
    cin >> fileName;
    inFile.open(fileName.c_str());
    if (inFile.fail())
    {
        cout << "Cannot open file " << fileName << endl;
        exit(1);
    }

    getData(Song, CAP, MAXCHAR);

    for (int i=0;i<CAP;i++)
    {
        cout << Song[i].title << " - "
            << Song[i].durMin << ":"
            << Song[i].durSec << endl;
    }

    cout << "Press any button to continue..." << endl;
    cin.get(); cin.get();

return 0;
}

void getData(songInfo Song[], int listSize, int charSize)
{


    for (int i = 0; i < listSize; i++)
    {
        cin.get(Song[i].title, charSize, ';');
        cin.get(Song[i].durMin, charSize, ';');
        cin.get(Song[i].durSec, charSize, '\n');
        i++;
        cin.ignore();
    }
}

程序正确编译而没有发生意外,但输出不是我想要的。会发生什么:

  1. Test.cpp打开songs.txt

  2. 将第一个char数组读入Song [i] .title,由&#39;;&#39;

  3. 分隔
  4. 将第二个字符读入Song [i] .durMin,由&#39;;&#39;

  5. 分隔
  6. 将第三个字符读入Song [i] .durSec,由换行符分隔

  7. 编译代码并运行后,我将其作为输出:

    ~/project2Test> ./test
    What is the file location?: songs.txt
    

    程序然后挂起来,我必须ctrl + C out

    首先,我做错了什么? 其次,我该如何解决搞砸的问题?

    另外,作为类规则的注释,我不允许使用除文件名之外的任何字符串。除此之外,所有单词都必须是字符。

2 个答案:

答案 0 :(得分:0)

对于像这样的问题,调试器绝对是一件好事。

您的挂起问题正在发生,因为在您的get_data函数中,您正在使用cin.get指示程序从标准输入文件获取输入。您打算使用您定义的文件&#34; inFile&#34;不是标准输入cin。

顺便说一下,我不清楚为什么你每次迭代for循环都会增加两次。

答案 1 :(得分:0)

使用inFile.get()而不是cin。您需要首先将inFile传递给函数。

在for循环中放置一个print语句,看看发生了什么。未来可能出现的问题是,如果你在Windows机器上并且有\ r \ n行结尾。 Unix使用\ n,Windows使用\ r \ n

相关问题