你的程序看起來不正確,它有一些錯誤,在其他答案中有詳細說明。
這是一個正確讀取歌曲列表的程序。請注意,這些是四個替代讀取文件的方法。選擇對你最有意義的一個,並刪除其他三個。
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <vector>
#include <iterator>
#include <algorithm>
struct Song
{
std::string title;
std::string artist;
int size;
Song() : size() { }
Song(const Song& song) :
title(song.title), artist(song.artist), size(song.size) { }
Song(std::string title, std::string artist, int size) :
title(title), artist(artist), size(size) { }
};
std::istream&
operator>>(std::istream& is, Song& song) {
return is >> song.title >> song.artist >> song.size;
}
int main()
{
std::vector<Song> songs;
std::ifstream fin;
fin.open("songlist.txt");
// You could read the songs this way:
std::copy(std::istream_iterator<Song>(fin),
std::istream_iterator<Song>(),
std::back_inserter(songs));
// Or, if you don't like std::copy, you can do this:
Song song;
while(fin >> song)
songs.push_back(song);
// Or, if you don't like operator>>(istream, Song), you can do this:
std::string artist;
std::string title;
int size;
while(fin >> artist >> title >> size)
songs.push_back(Song(artist, title, size));
// Or, if you don't like using the constructor:
while(fin >> artist >> title >> size) {
Song song;
song.artist = artist;
song.title = title;
song.size = size;
songs.push_back(song);
}
int num_songs = songs.size();
std::cout << "welcome to the show: " << num_songs << "\n";
return 0;
}
*「它可能是編譯器?」* ... erm ...不。另外,因爲這是C++而不是C,所以使用'std :: vector'併爲自己節省頭痛。由於'num_songs'沒有初始化,因此您當前創建了一個不確定大小的數組。另外,讀'num_songs'調用UB。很多問題在這裏... – 2012-02-23 22:27:56
啊這裏的幫助是無價的我現在正在工作,感謝所有和祝福 – gamergirl22 2012-02-23 23:58:43