从文件读取链表C++从 void* 到 char* 的转换无效

Invalid conversion from void* to char* C++ reading linked list from File

本文关键字:char 无效 转换 void 文件 读取 链表 C++      更新时间:2023-10-16

>im 尝试编写从文本文件读取到链表中

的程序

这是列表结构。

#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*我的所有 3 个 cin.getline() 语句。我需要能够从我的文件(Ranking.dbm)中逐行读取并将每组 3 行存储到 temp->video_nametemp->rankingtemp->url,然后创建一个新节点并保存接下来的 3 行......依此类推,直到我从文件中读取所有内容。

我该怎么做? 我是以一种完全错误的方式做到这一点,还是这只是一个语法错误? 我仍然掌握C++的窍门:/

这是

不正确的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;
}
getline(rankFile, temp->video_name); // You should write it this way