Zach P
Zach P

Reputation: 41

How to read in only numbers from a text file in C++

I am trying to read in the average rainfall for each month from a file that looks like this:

January 3.2 February 1.2 March 2.2

August 2.3 September 2.4

I need to take in the first 3 numbers and get the average of them along with output the 3rd month(March). I currently have this code:

#include <fstream>

#include <string>

using namespace std;

int main()    
{    
    ifstream inputFile;
    string name;
    double num = 0, many = 0, total = 0, value = 0;

    inputFile.open("Rainfall.txt");


    for (int count = 1; count <= 6; count++)
    {
        inputFile >> name;

        if (count == 1 || count == 3 || count == 5)
        {               
            continue;    
        }

        name += total;    
        cout << name << endl;     
    }

    for (int inches = 1; inches <= 6; inches++)
    {
        inputFile >> name;

        if (inches == 1 || inches == 3 || inches == 5)
        {
            continue;
        }

        cout << name << endl;
    }

    inputFile.close();          
    return 0;
}

And the output is looking like:

3.2
1.2
2.2
2.3
2.4
2.4

Now I can't add the first 3 numbers because they are strings and I need them to be doubles.

Upvotes: 2

Views: 1302

Answers (1)

Chad
Chad

Reputation: 19042

If the format name number is consistent, you can read it in trivially:

std::string name;
double number = 0, total = 0;

while(inputFile >> name >> number)
{
    cout << name << ' ' << number << '\n';
    total += number;
}

Upvotes: 4

Related Questions