fstream getline

Oct 13, 2013 at 10:25pm
I am having trouble reading from a file using fstream as taught by my professor. Reading from a txt of numbers I try to use:
1
2
3
4
5
6
7
8
9
10
11
int x[5];
fstream f;
	f.open("data.txt",ios::in);
	for(int i=0;i<=5;i++)
	{
		while(!f.eof())
		{
			f.getline(x[i],19,'/');
		}
	}
	f.close();


Where '/' is delimiter.
I don't understand any form of getline it's trying to make me retype and this site doesn't help me understand either. How would I read properly from a file using fstream?
Oct 13, 2013 at 10:37pm
Could you show a sample of the contents of the file data.txt please.
Oct 13, 2013 at 10:40pm
44
33
19
9
70
11


I was just using a delimiter as another example of what our professor lectured, but I can't seem to get it compiled either.
Last edited on Oct 13, 2013 at 10:40pm
Oct 13, 2013 at 10:45pm
Ok, here's one way:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    int x[5];
    
    ifstream f("data.txt");
    // read the numbers from the file
    int ix = 0;
    while (ix <5 && f >> x[ix])
        ix++;
         
    // show the contents of the array
    for (int i=0; i<ix; i++)
        cout << x[i] << endl;
        
    return 0;
}


The while condition may need some explanation. It is checking two separate conditions, first that the array is not full, then that reading of an integer has been successful.
Last edited on Oct 13, 2013 at 10:48pm
Oct 13, 2013 at 10:52pm
Using ifstream f>>x[i] to get numbers I get incorrect readings

[s]11 -858993460 -858993460 -858993460 -858993460
-858993460
[/s]

Nevermind the method I used to print cause this, thanks, but how would I use getline appropriately? And which is more sufficient ifstream or fstream?
Last edited on Oct 13, 2013 at 10:55pm
Oct 13, 2013 at 11:07pm
Here's an example using getline with a delimiter
input:
  545 / 7  / 9 /
11 / 210 /  32 /  17
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
#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

int main()
{
    int x[5];
    
    ifstream f("data.txt");
    
    int ix = 0;
    string line;
    while (getline(f,line,'/'))
    {
        x[ix] = atoi(line.c_str());
        
        ix++;
        
        if (ix >= 5)
            break;
    }
         
    for (int i=0; i<ix; i++)
        cout << x[i] << endl;
        
    return 0;
}

Output:
545
7
9
11
210


fstream can be used for either input or output (or both).
ifstream does the same job, but is for input only.
Topic archived. No new replies allowed.