Dec 9, 2018 at 4:12am UTC
Why is this returning some of the contents of the file mixed with garbage?
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 72 73 74 75 76 77 78
int main()
{
ifstream list, comparisonFile;
const int TEST_SIZE = 50,
NUM_STANDARD_ELEMENTS = 100;
int numElemsStandard = 0, numElemsList = 0,
value = 0,
stdList[NUM_STANDARD_ELEMENTS],
testList[TEST_SIZE], values = 0;
comparisonFile.open( "LSStandard.txt" );
if (comparisonFile)
{
for (int i = 0; i < NUM_STANDARD_ELEMENTS; i++)
{
comparisonFile >> stdList[i];
numElemsStandard++;
}
comparisonFile.close();
}
else
{
cout << "File could not be opened.\n" ;
}
list.open("LSTest.txt" );
if (list)
{
for (int k = 0; k < TEST_SIZE; k++)
{
list >> testList[k];
numElemsList++;
}
list.close();
}
else
{
cout << "File could not be opened.\n" ;
}
for (int k = 0; k < numElemsList; k++)
{
cout << testList[k] << ' ' ;
}
cout << "end of array one " ;
for (int i = 0; i < numElemsStandard; i++)
{
cout << stdList[i] << ' ' ;
}
// system ("pause");
return 0;
}// end function main()
the output is
17 11 10 41 26 43 30 55 39 43 48 11 42 10 103 43 55 88 77 33 23 32675 330178264 32766 330178260 32766 -1362254549 32675 4196083 0 4195208 0 330178264 32766 725871085 0 11341735 0 -1377271752 32675 330178480 32766 -1377325680 32675 330178260 32766 330178464 32766 -1360052632 32675 end of arrayone 104 51 64 75 11 54 62 67 39 97 57 19 25 67 93 77 29 17 29 103 82 12 93 39 11 109 36 83 78 67 43 85 55 88 106 37 49 44 25 82 30 76 99 79 20 63 88 68 83 32675 330178464 32766 4196083 0 725871085 0 64971124 0 -136229455632675 -1377306120 32675 -1360054192 32675 -1362302552 32675 -1362232236 32675 1 0 0 0 -1373563616 32675 -1365823912 32675 330179488 32766 -1362201958 32675 -1362298623 32675 6 0 -1362298496 32675 6299704 0 6299080 0 330179992 32766 330179976 32766 1 0 330179664 32766 -1362232236 32675
contents of the files:
LSStandard.txt
43
104
51
64
75
11
54
62
67
39
97
57
19
25
67
93
77
29
17
29
103
82
12
93
39
11
109
36
83
78
67
43
85
55
88
106
37
49
44
25
82
30
76
99
79
20
63
88
68
83
LSTest.txt
55
39
43
48
11
42
10
103
43
55
88
77
33
23
Last edited on Dec 9, 2018 at 4:13am UTC
Dec 9, 2018 at 4:25am UTC
Looks like you run
comparisonFile >> stdList[i];
100 times, but you don't have 100 items in your file, so these extractions aren't all successful.
But afterwards, you try to print the list anyway (100 times).
http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/
Perhaps you meant to do something more along the lines of:
1 2 3 4 5 6 7
for (int i = 0; i < NUM_STANDARD_ELEMENTS; i++)
{
if (comparisonFile >> stdList[i])
numElemsStandard++;
else
break ; // stop trying to get input from the file once we can't extract anything
}
Last edited on Dec 9, 2018 at 4:27am UTC