Help inputting text file into an array.

Hello all I am trying to input a text file into an array. The problem is the text file has ten rows and three columns that I need to work with. I am able to input the file into the array but don't know how to call on each item of the text file. The file name is "Weapons.txt" and here is what it looks like:

Pencil 1 1
Dagger 1 3
Sword 1 5
BownArrow 2 6
Shotgun 2 9
GreatSword 2 8
Whip 1 4
Axe 1 6
BattleAxe 2 7
Excalibur 2 10

The items need to be stored as three variables.
First column: string name
second column: int hands
and third column: int attackpower

How do I write this code so that I am able to work with each item?


http://www.cplusplus.com/doc/tutorial/files/

see the example in the "Text files" section, but where in that example the line gets printed to the screen:
cout << line << '\n';

you will have to parse that line and assign variables for name, hands and attackpower.

but a good first step will be printing the contents of your file to the console, just to make sure you're doing it right.

and here's a way of parsing your line:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

#include<string>
#include<iostream>
#include<sstream>
#include<vector>

int main()
{

	// example line
	std::string line("Pencil 1 42");

	// things to assign to (with some defaults)
	std::string name = "";
	int hands = 1;
	int attackpower = 1;

	std::istringstream ss(line);
	std::vector<std::string> vec;

	do
	{
		std::string sub;
		ss >> sub;
		vec.push_back(sub);
	} while (ss);
		

	name = vec.at(0);
	hands = atoi(vec.at(1).c_str());
	attackpower = atoi(vec.at(2).c_str());



	return 0;
}


it's not very elegant, but i'm supposed to be doing my own work too :)
Last edited on
I have this in my code so far. It reads in the text file into the array. but I have no Idea how to get each variable. I will read up on parsing.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main ()

{
	string array[10];
	short loop=0;
	string line;
	
	ifstream myfile ("Weapons.txt");
	if (myfile.is_open())
	{
		while (! myfile.eof())
		{
			getline (myfile,line);
			array[loop] = line;
			cout << array[loop] << endl;
			loop++;
		}
		myfile.close();
	}
	else cout <<"Unable to open file";
	
	return 0;
}
read my post again for a quick (dirty) example.
also, you're better off using std::vector containers rather than c-style arrays.
Last edited on
Topic archived. No new replies allowed.