Hey I'm trying to validate whether a string array contains an integer or not. I'm required to use a Boolean function that takes in the string array and an integer variable that will contain the integer equivalent to what is stored in the string array. The code I have below returns true every time even when the string contains no integer numbers.
bool Check(char arr[], int &num)
{
if (isdigit(arr[0])) {
num = arr[0];
returntrue;
}
elsereturnfalse;
}
int main()
{
char arr[] = "abc";
int num;
Check(arr, num);
if (Check == false)
cout << "This number is not an integer" << endl;
else
cout << "This number is an integer." << endl;
system("pause");
return 0;
}
If anyone can point me in the direction of understanding where I messed up I'd appreciate it.
Check(arr, num);
if (Check == false)
cout << "This number is not an integer" << endl;
else
cout << "This number is an integer." << endl;
//change those lines to
if(not Check(arr, num))
cout << "This number is not an integer" << endl;
else
cout << "This number is an integer." << endl;
Thanks ne555. After I change it, the program works. I just tried it with 1.23 in the char array, and outputted the value stored in num and I get 49. Why is that? If I increase the number stored in the array by 1, it goes from 49 to 50. It also says in exercise description that if char array has a floating point number in it like 1.23, it should store the whole number portion in the num variable. so num would output 1 in the main function.
bool Check(char arr[], int &num)
{
if (isdigit(arr[0])) {
num = arr[0];
returntrue;
}
elsereturnfalse;
}
int main()
{
char arr[] = "1.23";
int num;
Check(arr, num);
if (not Check(arr, num))
cout << num << " This number is not an integer" << endl;
else
cout << num << " This number is an integer." << endl;
system("pause");
return 0;