Necrode
Necrode

Reputation: 51

Finding non-digits in a vector

When I attempt to find any non-digits in a vector using "isdigit", it always seems to think there are non-digits, even when there aren't any.

Here is my code:

vector<double> nums;      // vector to hold numbers from the file.

bool Numbers::Read (istream& istr)  // read in the numbers from the file
{


ifstream inputFile("nums.txt");   // open the file for reading

if (inputFile)
{

float meanTotal = 0.0; // mean value
double result;  // result of the numbers being added together
double count;   // count the amount of items in the file

while (inputFile >> count)  // read the numbers into the vector
{

    nums.push_back(count);
    ++count;



}

float numsSize = nums.size();   // size of the vector


for(int i = 0; i < numsSize; i++)
{



    if(isdigit(nums.at(i)))
    {

    }
    else
    {
        cout << "File contains non-integers" << endl;
        return -1;
    }

}



/* ADD ALL OF THE NUMBERS TOGETHER */

for(int i = 0; i < numsSize; i++)   // store the summation of the vector
{
    result += nums[i];
}


/* FIND THE MEAN OF THE NUMBERS ADDED */

meanTotal = result/numsSize;

float mean = meanTotal;


float dev = 0.0;
float devResult = 0.0;
float devHold = 0.0;


for(int i = 0; i < numsSize; i++)
{
    dev += (nums[i] - mean) * (nums[i] - mean);
}

devHold = dev / numsSize;

devResult = sqrt(devHold);

if (numsSize == 0)
{
    cout << "UNDEFINED" << " " << "UNDEFINED" << endl;
}
else if (numsSize == 1)
{
    cout << mean << " " << "UNDEFINED" << endl;
}
else
    cout << mean << " " << devResult << endl;
}

return true;

}

I want to make sure there is nothing but white space and numbers in the text file. "isdigit" doesn't seem to work how I want it to. I'm assuming that even though the vector reads the file by skipping over everything that isn't a number, isdigit doesn't function the same way.

I realize now that "isdigit" doesn't work on doubles. So how can I check my input file for non-numbers?

Upvotes: 0

Views: 344

Answers (1)

jax
jax

Reputation: 747

The function isDigit and others like it all work with char types. Thus one you use it on a doulbe (conunt), you get wrong results.

Upvotes: 1

Related Questions