我想编写一个应用程序来跟踪相对较小的音乐库。应用启动后,该应用应从数据文件加载歌曲信息。它允许用户添加新歌曲。程序退出时,应用程序应将数据保存回相同的数据文件。但是代码似乎并不整洁。没有setw,代码有什么方法可以读取char吗?
例如,我想读取具有“;”的文件用作定界符或字段分隔符。每个记录以换行符结尾:
title;artist;1;11;album
title 2;artist 2;2;22;album 2
title 3;artist 3;3;33;album 3
代替:
title ;artist ;1;11;album
title 2 ;artist 2 ;2;22;album 2
title 3 ;artist 3 ;3;33;album 3
请注意,我不能使用字符串类和向量。我只能使用字符数组。
#include <fstream>
#include <iomanip>
using namespace std;
struct Song {
char title[10];
char artist[10];
int durationMin;
int durationSec;
char album[10];
};
void addSong(Song trackList[], int& size){
size++;
cout << "Enter Song Title: ";
cin.getline(trackList[size].title, 10);
cout << "Enter Artist: ";
cin.getline(trackList[size].artist, 10);
cout << "Enter track duration: ";
cin >> trackList[size].durationMin >> trackList[size].durationSec ;
cout << "Enter album: ";
cin.ignore();
cin.getline(trackList[size].album, 10);
}
const int SONG_CAP = 20;
int main() {
Song track[SONG_CAP];
ifstream infile;
ofstream outfile;
int size = 0;
char ch, answer;
char line[30];
infile.open("songs.txt");
if (!infile.is_open()){
cout << "File not found. Create a new list." << endl;
}
else{
while (infile.peek() != EOF){
size++;
infile.get(track[size].title, 10);
infile.ignore(1);
infile.get(track[size].artist, 10);
infile.ignore(1);
infile >> track[size].durationMin;
infile.ignore(1);
infile >> track[size].durationSec;
infile.ignore(1);
infile.get(track[size].album, 10);
infile.get();
}
}
do {
cout << "Do you want to add new songs (y/n)?" ;
cin >> answer;
cin.ignore();
if (answer == 'y'){
addSong(track, size);
}
} while (answer != 'n');
cout << "size: " << size << endl;
// write(outfile, track, size);
infile.close();
outfile.open("songs.txt");
for (int i = 1; i <= size; i++){
cout << left << setw(9) << track[i].title << ';' << left << setw(9) << track[i].artist << ';' << track[i].durationMin << ';' << track[i].durationSec << ';' << left << setw(9) << track[i].album << endl;
outfile << left << setw(9) << track[i].title << ';' << left << setw(9) << track[i].artist << ';' << track[i].durationMin << ';' << track[i].durationSec << ';' << left << setw(9) << track[i].album << endl;
}
outfile.close();
return 0;
}