4

テキストファイルからリンクリストに読み込むプログラムを書き込もうとしています

これがリスト構造です。

#include <iostream> 
#include <string>
#include <fstream>
using namespace std;


struct Video { 
char video_name[1024];      //  video name
int ranking;                // Number of viewer hits
char url[1024];             //  URL
Video *next;  // pointer to Video structure
}  *head = NULL;        // EMPTY linked list

読み取りコードは次のとおりです。

void load()
{
struct Video *temp;
temp = (Video*)malloc(sizeof(Video)); //allocate space for node 
temp = head;
ifstream rankFile ("Ranking.dbm");
if (rankFile.is_open())
{
    while ( rankFile.good() )
    {
        cin.getline(rankFile, temp->video_name, "\n");
        cin.getline(rankFile, temp->ranking, "\n");
        cin.getline(rankFile, temp->url, "\n");
        temp = temp->next; 

    }
    myfile.close();
}

else cout << "Unable to open file"; 

return ;

}

Ranking.dbm次のようなテキストファイルから読み取っています。

bagheera
20
bagheera.com
sushi
60
sushi.com
wicket
99
wicket.com
teek
100
teek.com

ただし、ファイルからの読み取り中に3つのステートメントInvalid conversion from void* to char*すべてでエラーが発生します。cin.getline()ファイル ( Ranking.dbm) から 1 行ずつ読み取り、3 行の各セットを に保存しtemp->video_name、新しいノードを作成して次の 3 行を保存temp->rankingできるようにする必要があります。temp->urlファイルからすべて。

これどうやってするの?私はこれを完全に間違った方法で行っていますか、それとも単なる構文エラーですか? 私はまだC++のコツをつかんでいます:/

4

2 に答える 2

5

これは誤った使用法ですstd::istream::getline()

cin.getline(rankFile, temp->video_name, "\n");

また、2つの入力ストリームが関係しているため意味がありません:cinrankFile。正しい呼び出し(ただし、最も望ましいわけではありません)は次のとおりです。

rankFile.getline(temp->video_name, 1023);

提案:

  • std::stringの代わりにchar[]を使用して使用しますstd::getline(in, std::string&)
  • これには使用できないため、を使用operator>>して読み取ります。intstd::getline()
  • すべての読み取り操作の結果を確認してください。
  • malloc()C++で使用newしないでくださいdelete
  • 必要がない場合は、動的に割り当てないでください。
  • std::vector<Video>たとえば、リストを自分で実装するのではなく、リストを保持するためにSTLコンテナの1つを使用します。

例えば:

struct Video { 
    std::string video_name;
    int ranking;
    std::string url;
};

std::vector<Video> load()
{
    std::vector<Video> result;
    std::ifstream rankFile("Ranking.dbm");
    if (rankFile.is_open())
    {
        Video temp;
        std::string line;
        while (std::getline(rankFile, temp.video_name) &&
               rankFile >> temp.ranking &&
               std::getline(rankFile, line) && // need to skip 'ranking's
                                               // unread new-line
               std::getline(rankFile, temp.url))
        {
            result.push_back(temp);
        }
    }
    else
    {
        std::cerr << "Unable to open file"; 
    }

    return result;
}
于 2012-10-07T18:21:59.053 に答える
0
getline(rankFile, temp->video_name); // You should write it this way
于 2012-10-07T18:21:50.963 に答える