using getline with file streams

I am to take data from a file, then calculate average rainfall and output the data to another file.

A sample of the input file would be this

Location A 500 30 35 40 45 50
Location B 600 35 40 45 50 55
Location C 700 40 45 50 55 60

Where 'Location A' would be the name of the site, '500' would be the elevation, and '30 35 40 45 50' is the rainfall each month. I know i need to use getline(inputFile, location, \t) to get the names of the sites, however i do not know where to place it in my code.

Here is the start of my loops where i suspect i should put it.

1
2
3
4
while (inFile >> location >> elevation >> precipAmount)
	{
		
		for (count; count <= 12; count ++)


Any help would be appreciated as ive been writing this program for the better part of three hours trying to get it right.

Last edited on
You have no any need to use std::getline. You can use operator >> for all your data because they are separated by whitespaces.
yes but i need to use getline because many of the names for the locations are two words, such as 'White Pine' and 'Aspen Falls' so when i need to get just those specific words, then the elevation, then do calculations with the rainfall.
Are the data items separated by spaces or some other character such as tab?
The sample here doesn't make that clear, though in the absence of other information, I'd assume all are separated by spaces.
Location A 500 30 35 40 45 50
Location B 600 35 40 45 50 55
Location C 700 40 45 50 55 60
Last edited on
Oh yeah sorry forgot. It looks like this in the .txt file.

1
2
3
Location A         500 30 35 40 45 50
Location B         600 35 40 45 50 55
Location C        700 40 45 50 55 60 


there is a tab between the location names, and then spaces between the altitude, and each precipitation amount, which is why i need to use the \t in the getline
Last edited on
You could do something like this:
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
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>

using namespace std;

int main ()
{
    ifstream infile("rainfall.txt");

    if (!infile)
    {
        cout << "error opening input file" << endl;
        return 1;
    }

    string line;
    string location;
    int elevation;

    while (getline(infile, line))
    {
        istringstream ss(line);
        getline(ss, location, '\t');
        ss >> elevation;
        cout << "Location: " << location << " Elevation: " << elevation << endl;
        // get rainfall here
    }

    return 0;
}

I don't know how to handle the rainfall data, as there are five values in the sample file, but earlier comments suggest there might be as many as 12. Maybe there are a variable number of figures? If all you need is the average, another while loop nested inside the current one would do.
Last edited on
Topic archived. No new replies allowed.