2012-10-07 30 views
4

我嘗試寫一個程序,從文本文件讀入一個鏈表從void *的轉換無效爲char * C++從文件讀取鏈表

這裏是表結構。

#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 

但是我收到一個錯誤說: Invalid conversion from void* to char*對於我的cin.getline()聲明中的所有3個語句,它是從文件讀取的。我需要能夠從我的文件(Ranking.dbm)中逐行讀取,並將每組3行存儲到temp->video_nametemp->rankingtemp->url,然後創建新節點並保存接下來的3行...等等等等直到讀入文件中的所有內容。

我該怎麼做?我是以完全錯誤的方式去解決這個問題還是僅僅是一個語法錯誤?我仍然得到C的掛++:/

+0

這是C++?看起來像一個奇怪的C混搭。 – chris

+1

對不起,我試圖轉移一箇舊的C程序工作在C++和即時通訊仍然得到我應該和不應該使用的竅門... – accraze

+0

字符數組更好地替換爲'std: :string'。 'cin.getline'然後將被替換爲'std :: getline'。節點最好是智能指針。 C++甚至有一個鏈表類 - 「std :: list」。 – chris

回答

5

這是不正確的使用std::istream::getline()

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

並沒有任何意義,因爲涉及兩個輸入流:cinrankFile。正確的調用(但不是最優選的)是:

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

推薦:

  • 使用std::string代替char[]並使用std::getline(in, std::string&)
  • 使用operator>>閱讀int,因爲您無法使用std::getline()
  • 檢查結果讀操作。
  • 在C++中不使用malloc()使用newdelete
  • 如果不需要動態分配。
  • 使用其中一個STL容器來保存列表,而不是自己實現,例如std::vector<Video>

例如:

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; 
} 
+0

''\ n「'會在這裏工作還是應該是'\ n''? –

+0

@CodingMash,因爲新行字符是默認字符,所以不需要。然而,類型是'char'而不是'char *',所以它應該是''\ n''。 – hmjd

+0

所以它看起來像'temp-> video_name'和'temp-> url',但是當我嘗試讀入'rankFile.getline(temp-> ranking,1);'我得到一個錯誤:'invalid從int轉換爲char *'我應該在int中讀取不同的東西嗎? – accraze

0
getline(rankFile, temp->video_name); // You should write it this way 
相關問題