Originally Posted by
trenzterra
I tried using this:
Code:
char * conz;
cin>>conz;
int z;
z = atoi(conz);
if (isalpha(z) != 0)
{
cout<<"No alphabets allowed.\n\n";
cin.get();
goto end;
}
else if (z > 1000000)
{
cout<<"Please do not enter numbers larger than 1,000,000. \n\n";
cin.get();
goto end;
}
However it returns an "No alphabets allowed" error even when I enter an integer, but only one that has more than 2 digits...
How do I get round this?
1st - you should be getting runtime errors because you have not allocated any memory for conz, so cin is overwiting memory it shouldn't be.
Better would be to use an array: char conz[256] = "";
Best would be to use std::string conz;
2nd - atoi will truncate at the first char it reaches, so something like 28gh890sf will end up just being 28. There is then no need to test with isalpha
3rd - isalpha expects a char input, not an int, though you will end up with an autmatic conversion (with a warning) but it won't give you the results you expect.
If you are happy with the truncation from my 2nd point then drop the isalpha, however, if you want to keep ALL the numbers and discard ONLY the letters or if you need to invalidate the entire answer if it contains alpha then you need to drop atoi and do an isalpha(char) on each of the chars of your array
Code:
#include <iostream>
using namespace std;
int main()
{
char conz[256]="";
cin >> conz;
for (int index = 0; index < 256 ; ++index)
{
if (conz[index] == '\0')//test for end of null terminated string
break;
if (isalpha(conz[index]))
{
cout<<"No alphabets allowed.\n\n";
cin.get();
exit(0);
}
}
if (atoi(conz) > 1000000)
{
cout<<"Please do not enter numbers larger than 1,000,000. \n\n";
cin.get();
exit(0);
}
cout << "Number is OK";
}