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;

}``````

## Recommended Answers

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.

do you know of the string class?

## All 5 Replies

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.

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?

do you know of the string class?

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

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";``````
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.