Angel Nunez Angel Nunez - 7 days ago 5
C++ Question

Input elements differ from output elements from files C++

I have been having some problems with my code. I was asked to input elements from an .dat file into an array. For class we have to do this for various files without knowing how many elements will be in each file. The only thing we know is that here will never be more then 5000 elements per file.

One of my input file has the following elements:

5.675207 -0.571210
0.728926 0.666069
2.290909 0.751731 2.004545 0.907396
0.702893 0.646427 5.909504 -0.365045
2.082645 0.871841 5.597107 -0.633507
6.117769 -0.164663 6.091736 -0.190282
5.571074 -0.653433 4.503719 -0.978307
3.983058 -0.745620
3.670661 -0.504729
5.857438 -0.413001


When I run my code:

#define _CRT_NONSTDC_NO_DEPRECATE
#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;

int main(int argc, char * argv[])
{
ifstream fin;
ofstream fout;

if (argc < 3)
{
cout << "Incorrect usage: prog.exe filenname number" << endl;
cout << "Exiting now, please try again." << endl;
return -1;
}

fin.open(argv[1]);
if (!fin)
{
cout << "Error opening file \"" << argv[1] << "\", exiting." << endl;
return -1;
}

fout.open(argv[2]);

int count = 0;
int word;
double points[5000];

while (fin >> word)
{
fin >> points[count];
++count;
}

fout << "Numer of points is: " << count/2 << endl;

for (int i = 0; i < count; i++)
{
fout << points[i] << " ";
}

fin.close();
fout.close();

return 0;
}


I outputted the elements just to make sure that they were properly inputted. I get the following and I don't know why.

0.675207 0.57121
0.728926 0.666069
0.290909 0.751731 0.004545 0.907396
0.702893 0.646427 0.909504 0.365045
0.082645 0.871841 0.597107 0.633507
0.117769 0.164663 0.091736 0.190282
0.571074 0.653433 0.503719 0.978307
0.983058 0.74562
0.670661 0.504729
0.857438 0.413001


The first digit is converted to a 0 for some reason and the negative ones become positive. Would anyone know why this is occurring?

Answer
int word;

is doing you no favours. First it's an integer so fin >> word only reads the integer portion of the inputs. 5.675207 is read as 5. the .675207 is left in the file stream for fin >> points[count]. Words isn't stored anywhere to the 5 is discarded but the .675207 lives on as 0.675207 in points[0].

Where the negative signs are going I didn't bother trying to figure out because

while (fin >> points[count])
{
    ++count;
}

fixes everything.

Comments