double input

My program seems to input the last line of my file twice.
is there some way of stopping this from happening?

the following are my input and output files
data.txt
hi eyes candy lollypop
phone key spot hell

result.txt
hi
eyes
candy
lollypop
phone
key
spot
hell
phone
key
spot
hell

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  #include <iostream>
#include <fstream>
#include <string>
using namespace std;
	ofstream outs;
	ifstream ins;
int main(){
	ins.open("data.txt");
	outs.open("results.txt");
    string names[4] = { " " };
   do{
        for (int index = 0; index <= 3; index++)
        {
            ins >> names[index];
            outs << names[index] << endl;
        }
    }while(!ins.eof());
	ins.close();
	outs.close();
	return 0;
}
Hello awesomesause,

Part of your problem has to o with the while condition. Checking here for eof does n always work the way you might thing. line 14 will reach eof and print to your output file before the while condition is reached.

Try this instead:

1
2
3
4
5
while (ins >> names[index])
{
	outs << names[index] << std::endl;
	index++;
}


When eof is reached the while loop will fail and the output file will be correct.

You will also have to change the size of the array in line 10 to handle the total number of words in the input file. And you will have to define "index" and initialize it to zero before you use it.

Hope that helps,

Andy
I was planning to run a function that sorts the string array but i can not use the example you provided because it will just take all the words at once
Topic archived. No new replies allowed.