Home How to read in only numbers from a text file in C++
Reply: 0

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

user6071
1#
user6071 Published in September 20, 2018, 10:22 pm

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.

share|improve this question
  • en.cppreference.com/w/cpp/string/basic_string/stof – arynaq Feb 12 at 21:14

1 Answer 1

active oldest votes
up vote 4 down vote
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.306163 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO