On October 08 2010 06:33 Adeny wrote:
This works fine...
LOLOL DISREGARD THIS ENTIRE MESSAGE
+ Show Spoiler +
This works fine...
int x = 0;
cin >> x;
if (cin.good() > 0)
{
cout << "user input is: " << x << endl;
}
else
{
cout << "user input is bad" << endl;
}
LOLOL DISREGARD THIS ENTIRE MESSAGE
+ Show Spoiler +
Ok, let's validate the input so that only digits between 0 and 9 will be accepted. If you use cin >> on an integer, your program will blow up if someone starts typing anything but strictly numbers. Because of that we have to jump hoops...
HUH, DISREGARD THIS LOL. It seems if you cin >> to an int, with characters and nonsense, the int stays 0... God damnit it.
+ Show Spoiler +
What it does is take the users input, places it in to a string. Now it dissects the string, and checks each character seperately if its ASCII value is above or below 48-57, which is 0-9 on an ASCII table (ASCII Chart). Then convers the string to an integer using atoi(), and finally checks if the ints value is above 0.
Chances are though, your professor doesn't expect that of you and just poorly worded the assignment, maybe he wants you to assume that a user will always input numbers, in which case simply doing the following should work:
+ Show Spoiler +
Also god damn conversions in C++, jeez.
HUH, DISREGARD THIS LOL. It seems if you cin >> to an int, with characters and nonsense, the int stays 0... God damnit it.
+ Show Spoiler +
#include <string>
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
cout << "Input number or w/e\n";
string input;
cin >> input;
for (int x = 0; x < input.size(); x++)
{
if ( input[x] < 48 && input[x] > 57 )
{
cout << "Only 0-9";
break;
}
}
int validated = atoi(input.c_str());
if (validated > 0)
{
cout << validated;
}
else
{
cout << "Number must be over 0\n";
}
getch();
return 0;
}
What it does is take the users input, places it in to a string. Now it dissects the string, and checks each character seperately if its ASCII value is above or below 48-57, which is 0-9 on an ASCII table (ASCII Chart). Then convers the string to an integer using atoi(), and finally checks if the ints value is above 0.
Chances are though, your professor doesn't expect that of you and just poorly worded the assignment, maybe he wants you to assume that a user will always input numbers, in which case simply doing the following should work:
+ Show Spoiler +
int input;
cin >> input;
if (input > 0)
{
// do whatever here
}
else
{
// tell the user his input was bad.
}
Also god damn conversions in C++, jeez.
Seems to me you need some help aswell.
You can use :
if(cin.fail()){
// print bad stuff
return -1;
}
Alternatively you can set cin.exceptions(istream::failbit) and catch istream::failure exception.
if (input[x] < 48 && input[x] > 57 )
You don't have to use 48 or 57 but :
if (input[x] < '0' && input[x] > '9' )
does the same.
Edit : Oh ok, you have edited the former message..