Reading a .txt file into an array

I am writing a program in Dev C++ to read values from a .txt file into a series of arrays. The program I have written so far compiles and starts to run, but on the output some of the values are wrong, and after several lines the programs crashes. I attempted to debug it, and the compiler suggests that the problem might be where I am reading the file into the program, but I can't figure it out.

Here is my program:

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
#include<iostream>
#include<math.h>
#include<iomanip>
#include<fstream>
#include<string>

using namespace std;

int main(void){

    string fileName=" ";
    ifstream file;
    int rows(0), termsOne[rows], termsTwo[rows], columns(0), limitOne(0); 
    int limitTwo(0), i(0);
    double valueX[rows], sinX[rows], sinOne[rows], errorOne[rows];
    double sinTwo[rows], errorTwo[rows];
    
    cout<<"filename?  >>  ";
    cin>>fileName;
    
    file.open(fileName.c_str());
    
    if(file.fail())
        cout<<"File did not open properly.";
        
    file>>rows>>columns>>limitOne>>limitTwo;
    
    for(i=0;i<rows;i++){
         file>>valueX[i]>>sinX[i]>>sinOne[i]>>termsOne[i]>>errorOne[i]
         >>sinTwo[i]>>termsTwo[i]>>errorTwo[i];//I think the problem is here

         cout<<valueX[i]<<"  "<<sinX[i]<<"  "<<sinOne[i]<<"  "
         <<termsOne[i]<<"  "<<errorOne[i]<<"  "<<sinTwo[i]
         <<"  "<<termsTwo[i]<<"  "<<errorTwo[i]<<endl;
    }
    
    system("pause");
    file.close();
    return(0);
    
}


The file I am trying to read in has 4 numbers on the first row and 8 numbers on each row after that(it is a table of values comparing sin(x) to a taylor series expansion).
Dev C++ is evil (I am so tired of saying this all the time -__-)

What does your actual file look like?

(Unrelated: Does anyone know if fstream will gets a std::string overload for open in 0x? If feels wrong for a C++ class to require a cstring...)

EDIT: Ah no wait, this is actually pretty easy:

Your arrays all have 0 elements, you seg fault when you try to access them, because you only change row afterwards.
Last edited on
line 13 does normally not compile. Anyway 'termsOne' (and following) is an array of size 0 and does not expand even if you change 'rows'. Use dynamic arrays like std::vector instead


http://www.cplusplus.com/reference/stl/vector/
Last edited on
I declared the arrays after the value for rows and now it works thank you so much.
Topic archived. No new replies allowed.