954,483 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

C++ Real and Integer Numbers in a Text File

I need help in reading a text file and by using a switch statement the user can either press 1 to find the average of all the integers in the text file, and by pressing 2 they find only the averages of the real numbers in said file. This is my code thus far and my problem/question is how do you distinguish +- numbers from +- numbers that have a decimal, ie real numbers from integers.

#include <iostream> 
#include <fstream> 

using namespace std; 

int main() 
{ 
    int n;
    double average(0), sum(0), count(0);
    
    ifstream data;
    data.open("data.txt");  
    
    if(data.fail( ))
    { 
        cout << "Error Opening File"<<endl; 
        return 2;
    }
    

    
        while(!data.eof())
    {
        data>>n;
        sum=sum+n;
        count++;
    }

    int rank;
    cin >> rank;

    
    switch(rank){
                 
    case 1:
    average=(sum)/(count);
    cout << "The Average Is: " << average << endl;
    break;

}
    
    data.close();     
    
    cout << endl;
    system("PAUSE");
    return 0;

}
tKc
Newbie Poster
23 posts since Oct 2010
Reputation Points: 10
Solved Threads: 0
 

you cant because you are reading the file into an int. you will need to read it into a string and then test to see if has a decimal or not.

NathanOliver
Veteran Poster
1,084 posts since Apr 2009
Reputation Points: 215
Solved Threads: 189
 
you cant because you are reading the file into an int. you will need to read it into a string and then test to see if has a decimal or not.


How do i do this?

tKc
Newbie Poster
23 posts since Oct 2010
Reputation Points: 10
Solved Threads: 0
 

do you know of the string class?

NathanOliver
Veteran Poster
1,084 posts since Apr 2009
Reputation Points: 215
Solved Threads: 189
 

yes, just how do u test it if it has a decimal or not

tKc
Newbie Poster
23 posts since Oct 2010
Reputation Points: 10
Solved Threads: 0
 

to test if it has a decimal you can do something like

size_t spot;
string test = "123.456789";
spot = test.find_first_of(".",0)
if (spot == std::string::npos)
    cout << "there is a decimal";
NathanOliver
Veteran Poster
1,084 posts since Apr 2009
Reputation Points: 215
Solved Threads: 189
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: