[英]Reading a text file into a struct array c++
这是用于家庭作业的,但是我要介绍的是针对我的大部分作业的小型测试程序。
首先,我将在文件“ 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();
}
}
该程序可以正确编译而不会发生意外,但是输出不是我想要的。 应该发生什么:
Test.cpp打开songs.txt
将第一个字符数组读入Song [i] .title,以';'分隔
将第二个字符读入Song [i] .durMin,以';'分隔
将第三个字符读入Song [i] .durSec,以换行符分隔
编译并运行代码后,将其作为输出:
~/project2Test> ./test
What is the file location?: songs.txt
该程序然后挂在这里,我必须按ctrl + C退出
首先,我在做什么错? 第二,我该如何解决自己搞砸的问题?
另外,作为类规则的注释,除文件名之外,不允许使用任何字符串。 除此之外,所有单词都必须是字符。
对于这样的问题,调试器绝对是一件好事。
之所以会出现挂起问题,是因为在get_data函数中,您正在使用cin.get来指示程序从标准输入文件中获取输入。 您打算使用定义的文件“ inFile”而不是标准输入cin。
顺便说一句,我不清楚为什么您要在for循环的每次迭代中将i递增两次。
使用inFile.get()代替cin。 您需要先将inFile传递给函数。
将打印语句放在for循环中以查看发生了什么。.将来可能出现的问题是,如果您在Windows计算机上并且行尾有\\ r \\ n。 Unix使用\\ n,Windows使用\\ r \\ n
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.