Reading in arrays from file

I know the code is horrible and I'm sorry for that. I'm new to programming. I'm trying to read in a list of numbers like this:

3 3 15
123 5 4 3
124 2 5 5
125 3 5 2

It successfully opens the file, but I can't get it to read in the numbers. I'm trying to avoid multi-dimensional arrays. Any help would be greatly appreciated.


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

# include <iostream>
# include <fstream>
# include <string>



using namespace std;

const int  fileNameSize  =  32;


 int  main()
  {

    int lineCount;
	ifstream  ins;
	
	
    char fileName[fileNameSize];

    cout  <<  "Enter filename: ";
    cin   >>  fileName;

    ins.open( fileName );
 
    if  ( ins.fail() )
    {cout  <<  "Error opening the file: "  <<  fileName <<  endl;}
    
	else
    {cout  <<  "Successfully opened file: " << fileName <<  endl;


ins.close();


return 0;


string line;
lineCount = 0;
getline(ins, line);
while (line.length() != 0)
{
	lineCount++;
	getline (ins,line);
}

    }


cin.get();
cin.get(); 
    return  0;
  }

Do you want to read all the numbers into a single 1D array? If so:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#incluide <iostream>
#incluide <vector>

int main()
{
    std::vector<int> a;
    int n;

    std::ifstream is("numbers.txt");
    while (is >> n)
        a.push_back(n);

    return 0;
}
I actually want to read it in one line at a time. I added the code below and it now reads in the whole file, except the last line, but I want to read in one line at a time and break that down into an array with it able to identify separate parts, for example,

line one:
cout << array[0] << endl; with the first number being displayed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

string line;
lineCount = 0;
getline(ins, line);

while (!ins.eof())
{
	lineCount++;
	cout << line << endl;
	getline (ins,line);
	
	
}


Don't test for eof, test the stream state directly.
whats wrong with testin eof?

not trying to hijack but I have code in my assignment I just did as so:

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

void inputArray()
{
    try
    {
        ifstream input( getInputFileName().c_str() );
        string line;
        int count = 0;

        if ( ! input.is_open() )
        {
            cerr << "Failed opening input";
            exit(1);
        }

        while ( ! input.eof() )
        {
            getline( input, line );
            array[count++] << line;
        }
    }
    catch (...)
    {
        cerr << "Error processing file to array";
        exit(1);
    }
} 

Last edited on
Topic archived. No new replies allowed.