Getting content of text file and putting it in an array

Hello

I've got a question but don't really know how to explain it. But I'll try it.

I have a text file including names, now my code should take those names put them in an array, and then display it.

Text file (names.txt):
Sam
Kim
Adrian
Hendrik


Psuedo code:
1
2
3
4
5
6
7
int names[] = {

}
names[] = names.txt
for (int i = 0; i < length(names.txt); i = i + 1) {
cout<<names[i]<<endl;
}


Of course that code doesn't work, but it's a good way to explain what I want (I hope). :)

Thanks for reading,
Niely
you need to open the file using ifstream and reads its contents.
store it in a temporary variable and then read out the results

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
#include "stdafx.h"
#include <fstream>
#include <string>
#include <vector>
#include <iostream>

std::vector<std::string> names;

int main() 
{ 
	// specify the path where the file is stored.
    std::ifstream file("C:\\Temp\\names.txt");
    
   std::string str; 
    
    // store items in names
	while (std::getline(file, str))
    {
        names.push_back(str);
    }

 // output results
  for (int i=0; i < names.size(); i++)
   std::cout << names[i] << std::endl;

  int x;
  std::cin >> x;
}
^Thanks a lot for your reply!
Extremely useful! :D
Topic archived. No new replies allowed.