print out text file content into string array

Dec 29, 2016 at 9:56pm
i Would like to print out an entire text file into the string array insert.


#include <iostream>
#include <string>
#include <algorithm>
#include <fstream>

int main()
{
int i =0;
std::string insert[] = {};
std::ifstream in("example.txt") ;
while(in)
{
insert[i] >> in;
std::cout<<insert[i]<<"/n";
i++;
}

}
Dec 29, 2016 at 11:33pm
I'm not sure how this compiles.
std::string insert[] = {};
This is a string array with 1 element: an empty string.
insert[i] >> in;
in has to be on the left hand side of operator>>.
1
2
3
4
5
6
while(in)
{
insert[i] >> in;
std::cout<<insert[i]<<"/n";
i++;
}

When i = 1, you will be accessing an element outside the bounds of the array, resulting in undefined behaviour. Consider using a vector.
std::cout<<insert[i]<<"/n";
It's '\n' and not '/n'.
Dec 30, 2016 at 12:10am
closed account (48T7M4Gy)
If a C style array is used, either estimate the size of the array, ie number of words to be encountered and apply limits to the read to ensure no undefined behaviour or, make a first read of the file to count the number of words and then a second read to fill the array.
Dec 30, 2016 at 12:12am
tyvm! both helpful.
Dec 30, 2016 at 4:58am
closed account (iTpkjE8b)
forgot but i think ostream where you could read the text in there as data. I really forgot. Just came on here to review c++ and see what others have for questions
Dec 30, 2016 at 5:02am
forgot but i think ostream where you could read the text in there as data. I really forgot. Just came on here to review c++ and see what others have for questions

ifstream is used for file input. ofstream is used for file output.
Topic archived. No new replies allowed.