How can i input data from a txt file into the objects of a class. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How can i input data from a txt file into the objects of a class.

I've been trying to do a program that can read a text file and copy its content in their corresponding class attributes. The class is called Headquarters every hq has a name, a direction and two coordinates x and y. Most of my problems come from the fact that the number of Heardquarters are decided by the user. class Heardquarters{ public: int x; int y; char direction[100]; char name[100]; }hq[20]; The text from the file looks like this: venezuela,caracas,2,4 india,delhi,2,3 usa,missouri,3,2 At first i tried using a for loop with file >> hq[i]name >> direct but that copies the entire row into the name and direction. Then i tried using file.getline(hq[i].direction,100,','); but that only works on the char it ignores the int x and y coordinates. I also tried to do this to assign values to the coordinates but it didnt work. file.getline(y,'\n'); switch (y) { case '1':hq[i].y=1;break; case '2':hq[i].y=2;break; case '3':hq[i].y=3;break; case '4':hq[i].y=4;break; case '5':hq[i].y=5;break; case '6':hq[i].y=6;break; case '7':hq[i].y=7;break; case '8':hq[i].y=8;break; default: break; } Long story short i need to copy the content from an text file into a class with 2 char and 2 int attributes, and right now im having trouble making the program load the int values from the .txt, sorry for the poor redaction and english.

1st Apr 2022, 7:27 PM
M&M
M&M - avatar
0 Answers