writing lines of text file into Array of strings

Hello,

I'm trying to write a program that takes a line of text from a .txt file and then writes that line into an array of strings.

So far I figured out to put one word of text in each row of the Array, but I want to put a whole line so:
"first line from text" will be put into textArray[0]
"Second line from text" will be put into textArray[1]
etc...

So far this is what I have:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;

int main(int argc, char *argv[]) {
	ifstream file("text.txt");
	string textArray[100];
	if(file.is_open()){
		for(int i = 0; i < 100; i++){
			file >> textArray[i];
		}

	}
		for(int i = 0; i < 100; i++){
			int j = i + 1;
			cout << j << ": " << textArray[i] << endl;
		}
		file.close();
	return 0;


Thanks for the help!
Last edited on
Use getline:
 
  getline (cin, textArray[i]);


Using a for loop is poor design. Your loop is expecting exactly 100 lines.
Better design is to use a while loop:

1
2
3
4
  int i = 0;

  while (i < 100 && getline(cin,textArray[i++]))
    ;


PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.
Last edited on
It works! Thanks so much! :D
Topic archived. No new replies allowed.