Trying to get a text file into an array

Hello,

I am trying to get a text file into an array, here is what I have as code:


// ifstream constructor.
#include <iostream>
#include <fstream>
using namespace std;

int main () {

string test[10];
int counter = 10;


ifstream ifs ( "items.txt" , ifstream::in );
while (ifs.good())
{
cout << (char) ifs.get();
test[counter] = ifs.get()
counter--;
}

ifs.close();


for(int i = 0; i < 10; i++)
{
cout << test[i] << endl;
}


return 0;
}





It is not working, says bus error, any ideas?

Thanks
Try this:

1
2
3
4
5
6
ifstream ifs ( "items.txt" , ifstream::in );
for(int i = 0; i < 10 && ifs.good(); i++)
{
    cout << (char) ifs.get();
    test[i] = ifs.get()
}


It may be because the your program reads an additional word and trying to assign it to your array. With this loop, you ensure that only 10 words are allowing to be read.

Another thing, next time use [code][ /code] wrapper to make your code readable, and use indents.
Last edited on
If it's words you are reading to the array you can use operator>>.
Please use [code][/code] tags

The problem is that you are writing outside array boundaries when the file contains more than 10 characters.
Either add a condition to your loop checking that counter is not less than 0 or use ifs.read
http://www.cplusplus.com/reference/iostream/istream/read/
Topic archived. No new replies allowed.