Validate Input Exercise

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
bool Check(char arr[], int &num)
{
	if (isdigit(arr[0])) {
		num = arr[0];
		return true;
	}
	else
		return false;
}


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.
Last edited on
1
2
3
4
5
6
7
8
9
10
	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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

bool Check(char arr[], int &num)
{
	if (isdigit(arr[0])) {
		num = arr[0];
		return true;
	}
	else
		return false;
}


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;
Last edited on
> outputted the value stored in num and I get 49. Why is that?
https://en.wikipedia.org/wiki/ASCII#Printable_characters

> if char array has a floating point number in it like 1.23,
> it should store the whole number portion in the num variable
http://www.cplusplus.com/reference/string/stoi/
Topic archived. No new replies allowed.