Reading Strings from a file.
Hi all, I'm pretty new at programming and have some big troubles with the following program. I hope someone can give me some tips so I can continue.
First of all I made a class URL_Keyword_Mapping, which has 3 private arguments: an url (string), a keyword (string) and a weight (int).
Code:
class URL_Keyword_Mapping{
private:
std::string url;
std::string keyword;
int weight;
}
Now I am receiving a certain .txt file and I need to read the arguments and put them in an array of URL_Keyword_Mapping objects.
Here is an example of the structure of the given file:
http://www.youtube.com youtube 90000 videos 80000
http://www.google.com cars 20000 dogs 30000 cats 25000
The url is only used only once, so actually there are 5 objects up there:
- http://www.youtube.com, youtube, 90000
- http://www.youtube.com, videos, 80000
- http://www.google.com cars 20000
- http://www.google.com dogs 30000
- http://www.google.com cats 25000
Here is my method:
Code:
URL_Keyword_Mapping* read(std::ifstream& ifile, int& length) {
URL_Keyword_Mapping Array[50];
int i = 0;
std::string test;
while (ifile.eof()) {
ifile >> Array[i].url >> Array[i].keyword >> Array[i].weight; // Reading first 3 arguments
ifile >> test;
while (test != '\n') { // Check if you reached end of the line or not
Array[i+1].url = Array[i].url;
Array[i+1].keyword = test;
ifile >> Array[i+1].weight;
ifile >> test;
i++;
}
i++;
}
return Array;
}
Short explanation: First we read the first 3 arguments and put them in our first array object. We read the next argument, but don't know sure if there are any. But, if there are, it will only be a new keyword + weight, because the URL is only placed once at the beginning of each line.
If there are still strings to come, we put them in the next array object and repeat the process. As soon as we meet a newline character, we go out of the loop and repeat the process for the next line.
Problems: I'm getting like 20 errors about the test = '\n' comparation. I don't really know how to solve the problem =/.