C++ 在向量中查找非数字
当我试图用“isdigit”查找向量中的任何非数字时,它似乎总是认为存在非数字,即使没有 这是我的密码:C++ 在向量中查找非数字,c++,vector,C++,Vector,当我试图用“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
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;
}
向量nums;//矢量来保存文件中的数字。
bool Numbers::Read(istream&istr)//从文件中读入数字
{
ifstream inputFile(“nums.txt”);//打开文件进行读取
如果(输入文件)
{
float meanstotal=0.0;//平均值
double result;//数字相加的结果
重复计数;//计算文件中项目的数量
while(inputFile>>count)//将数字读入向量
{
nums.推回(计数);
++计数;
}
float numsize=nums.size();//向量的大小
对于(int i=0;i cout函数isDigit和其他类似的函数都适用于字符类型。因此,如果在doulbe(conunt)上使用它,则会得到错误的结果。isDigit
适用于字符(text)是的,你是对的。我是愚蠢的。你是对的。那么……在那种情况下,你怎么能检查文本文件中的非数字?是的。我刚刚意识到。那么我怎样才能检查文件的非数字呢?我对C++非常陌生。非数字应该很可能是字符类型。只是把它当作字符,而不是数字来读取。n如果你想让数字成为数字,使用stat_cats(count)将其转换为数字。另外,你不需要让count有一个double,int是可以的。所以我需要先将我的向量类型更改为char,当我在中读取值时,将它们转换为数字?是的。仅当需要数字时才将它们转换为数字