Incorrect conversion from void * to char * C ++ reading linked list from file

im trying to write a program that reads from a text file into a linked list

here is the list structure.

#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 

here is the code to read:

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

it is read from the text file Ranking.dbm , which looks like this:

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

however, I get an error: Invalid conversion from void* to char* in all 3 of my cin.getline() statements while reading from a file. I need to be able to read line by line from my file ( Ranking.dbm ) and store each set of 3 lines until temp->video_name , temp->ranking and temp->url , and then create new nodes and save the next 3 lines. .. so on and so forth until ive reads everything from the file.

How can i do this? Am I talking about this completely wrong or is it just a syntax error? I am still getting C ++ freeze: /

+4
source share
2 answers

This is the wrong use of std::istream::getline() :

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

and it makes no sense, since two input streams are involved: cin and rankFile . The correct call (but not the most preferred):

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

Suggest:

  • using std::string instead of char[] and use std::getline(in, std::string&) .
  • use operator>> to read int since you cannot use std::getline() for this.
  • check the result of each read operation.
  • do not use malloc() in C ++ use new and delete .
  • Do not dynamically allocate unless you need to.
  • use one of the STL containers to store the list, and not to implement it, std::vector<Video> , for example.

For instance:

 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; } 
+5
source
 getline(rankFile, temp->video_name); // You should write it this way 
0
source

Source: https://habr.com/ru/post/1438287/


All Articles