Edvinas Sadeckas Edvinas Sadeckas - 1 year ago 146
C++ Question

Reading from text file to structure

Firstly, I'd like to explain what I'm trying to do. So, I have a text file with 10 names followed by their points. I'm trying to create a structure and read information from a file using a function (void). And that's my code and text file:


#include <iostream>
#include <fstream>
#include <string>

using namespace std;

void read(struct laLiga t[]) {
ifstream infile("info.txt");
int i = 0;
while(infile >> t.team[i] >> t.points[i]) {
infile >> t.points;

struct laLiga {
char team[50];
int points;

int main() {
struct laLiga t[10];
return 0;

text file:

Athletic Bilbao 15
Atletico Madrid 18
Barcelona 16
Alaves 10
Las Palmas 12
Real Madrid 18
Real Sociedad 10
Sevilla 17
Eibar 11
Villarreal 16

Answer Source

First of all, you need to define the structure before you use it in the read function.

Secondly, in the read function it is the variable t that is an array, not its members. So you should be using t[i].team and t[i].points.

Thirdly, you have already read the data from the file with the >> operators in the loop condition. You should not read it again inside the loop.

Fourthly, the input file you want to read is actually harder to parse than you think. That is because you can have names both without and with spaces in them. Both the get function of input streams and the input operator >> separates on spaces. You should probably read the whole line and then split it at the last space.

Lastly, and actually a reason I should not write an answer is that you haven't actually asked a question, or told us what is wrong with your code. Please read about how to ask good questions for future questions.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download