当我尝试使用" isdigit"在向量中找到任何非数字时,它似乎总是认为有非数字,即使没有任何数字。
这是我的代码:
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;
}
我想确保文本文件中只有空格和数字。 &#34; ISDIGIT&#34;似乎并不像我想要的那样工作。我假设即使向量通过跳过不是数字的所有内容来读取文件,也不会以相同的方式运行。
我现在意识到&#34; isdigit&#34;没有双打工作。那么如何检查输入文件中的非数字呢?
答案 0 :(得分:1)
函数isDigit和其他类似的函数都使用char类型。因此,你在doulbe(conunt)上使用它,你会得到错误的结果。