-1

Apologies if this question is stupid, I'm new to coding, especially in C++. I'm trying to read in data points from a space-separated text and then use the printf function to get it output them to the console. When I try this;

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main() {
    double x[1000];
    int i = 0;
    int j;
    double y[1000];
    double sigmay[1000];

    ifstream dataFile("xys_test.txt");

    if (dataFile.is_open()) {
        while (!dataFile.eof())
        dataFile >> x[i] >> y[i] >> sigmay[i];
        printf("x = %5.2f, y = %5.2f, sigmay = %5.2f\n", x[i], y[i], sigmay[i]);
    i++;
}
}

All the console output gives me is the last data point, when I was hoping that all the points would be output into the console. How can I resolve this?

R L W
  • 137
  • 9

3 Answers3

2

You are missing a pair of { ... } for the contents of your while block. Currently, only the dataFile >> x[i] >> y[i] >> sigmay[i]; line is inside the while block.

if (dataFile.is_open()) {
    while (!dataFile.eof()) {
        dataFile >> x[i] >> y[i] >> sigmay[i];
        printf("x = %5.2f, y = %5.2f, sigmay = %5.2f\n", x[i], y[i], sigmay[i]);
        i++;
    }
}
Vladimir Panteleev
  • 24,651
  • 6
  • 70
  • 114
2

you lost your curly bracket,

while (!dataFile.eof()) {
  dataFile >> x[i] >> y[i] >> sigmay[i];
  printf("x = %5.2f, y = %5.2f, sigmay = %5.2f\n", x[i], y[i], sigmay[i]);
  i++;
}
ibrohimislam
  • 717
  • 7
  • 21
2

The code should be:

while ( i < 1000 && (dataFile >> x[i] >> y[i] >> sigmay[i]) )
{
    printf("x = %5.2f, y = %5.2f, sigmay = %5.2f\n", x[i], y[i], sigmay[i]);
    ++i;
}

You should test whether or not the read operation succeeded, in order to decide whether to proceed with printing and committing the data. Testing eof is irrelevant and a mistake.

Also #include <cstdio> should be used for printf. Possibly your compiler/library setup involves cstdio being included by iostream but in general that is not the case.

Community
  • 1
  • 1
M.M
  • 138,810
  • 21
  • 208
  • 365