Reading File into Arrays

For class I need to read an id number from a file, and a name that is next to the id number, it seems as if it is a tab delimited file.
I want to learn how to read a file into an array so that I can search the Array for the correct id and then the name. I already know how to search an Array, so this is just a matter of reading the file into an Array.
Can someone help me?
Are you familiar with <fstream>?
Read the file into the array just as you would read the file into cin or ifstream.
This automatically ignores tabs, spaces... (any whitespace)
This may help you:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
#include <fstream>

int main()
{
    using namespace std;

    ifstream file("file.txt");
    if(file.is_open())
    {
        string myArray[5]; // or whatever size you need

        for(int i = 0; i < 5; i++) // change 5 to the same size as above
        {
            file >> myArray[i]; // strings are stored in the array at position[i]
        }
    }

}
Last edited on
Can you specify a size for a regular string? I thought you could only specify the size of a c-string.
I am not sure what you are asking. The program compiles and runs fine, as intended.
I just realized this would not store both the user ID and name as one string, one element of the array. Here is the revised code. Please let me know if you have questions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
const int NUM_NAMES = 10; // change this to whatever size you need

int main()
{
	ifstream fin("file.txt"); // rename file.txt to whatever your filename is
	string myArray[NUM_NAMES];

	for (int i = 0; i < NUM_NAMES; i++) // keep reading until at end of array
	{
		getline(fin, myArray[i], '\t'); // gets ID and name (tab delimited). Stores in array at (i)
		cout << myArray[i] << endl; // prints contents of array on console
	}
	cin.get(); // pauses until keystroke
return(0);
}
Last edited on
Topic archived. No new replies allowed.