off by one error

Jan 22, 2014 at 5:07am
This is supposed to read in from a file a date, sender, recipient, and body (respectively). I have 5 sets in my local file for testing but my output is always off by one. it reuses all of the information from the last read in.

I have a sneaking suspicion that the problem is occurring in the condition of my first for loop but I don't understand what is going on to solve it.

What is causing the off by one? How can I fix it?
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <iostream>
#include <fstream>
#include "Message.h"

using namespace std;

void bubbleSort( Message[], int );

int main()
{
    Message m[1000];
    string date, sender, recipient, body;
    ifstream in;
    int count = 0;

    in.open("messages.txt");
    if ( !in )
    {
        cerr << "nope.";
        return 1;
    }
    
    for( int i = 0; i < 1000 && in; i++ )
    {
        getline(in, date);
        getline(in, sender);
        getline(in, recipient);
        getline(in, body);
        
        m[i].setDate(date);
        m[i].setSender(sender);
        m[i].setRecipient(recipient);
        m[i].setBody(body);
        
        count++;
    }

    bubbleSort( m, count );

    for( int i = 0; i < count; i++ )
    {
        cout << m[i].toString() << endl;
    }

    in.close();

    return 0;
}


void bubbleSort( Message array[], int size )
{
    Message temp;
    bool swapped = true;
    
    do
    {
        swapped = false;
        for( int i = 0; i < size; i++ )
        {
            if( array[i].getDate() < array[i + 1].getDate() )
            {
                //switch the objects
                temp = array[i];
                array[i] = array[i + 1];
                array[i + 1] = temp;
                swapped = true;
            }
        }
    }while(swapped);
}



text file:
2010/01/19
me
you
first
2011/01/19
me
you
second
2012/01/19
me
you
third
2013/01/19
me
you
fourth
2014/01/19
me
you
fifth


example output:
messageID: 5
date: 2014/01/19
sender: me
recipient: you
body: fifth

messageID: 6
date: 2014/01/19
sender: me
recipient: you
body: fifth

messageID: 4
date: 2013/01/19
sender: me
recipient: you
body: fourth

messageID: 3
date: 2012/01/19
sender: me
recipient: you
body: third

messageID: 2
date: 2011/01/19
sender: me
recipient: you
body: second

messageID: 1
date: 2010/01/19
sender: me
recipient: you
body: first
Jan 22, 2014 at 6:30am
I fixed it by changing the for loop to

for( int i = 0; i < 1000 && (getline(in, date) && getline(in, sender) && getline(in, recipient) && getline(in, body)); i++ )

I am not sure why it worked, but it did.
Topic archived. No new replies allowed.