-
Loops
I'm trying to create a code that will ask the user for a number and then perform some calculations based on that number. What I want the program to do is:
If I type a character, the program will display a message and then take me back to the beginning of the program, where I can input again.
If I type a number the program is to carry on normally.
I assume I have to use loops for this but I have no idea how to do that. Could anyone help me out?
-
yeah, the easiest way would be to use a loop, here is a small example of what you want to do:
(its pseudocode by the way)
int main ( void )
{
loop ( ) ...
{
cin >> char_which_was_inputted;
if ( isalpha ( char_which_was_inputted ) )
display message
else if ( isdigit ( char_which_was_inputted ) )
break; //breaks out of the loop
}
...rest of program goes here...
return 0;
}
-
That might be a little tricky, because it involves determining what data type you entered, and I don't think that's possible (if it is, I need to do that in a C++ decoding program I'm making, so please tell me if you can!). You could convert them to integers to get the ASCII value, and then if it's between 97 and 122, it's a lowercase letter, if it's between 49 and 57, it's a number, and if it's between 65 and 90, it an uppercase letter. Use ifs for that, and if it's a number, use a switch statement to assign the value to an int, which you can't do directly since it's a char at this point. Good luck.
-
Let's just say I'm pretty confused right now :D
I'll take you advice but I don't think I have the skills to do something like that yet...
-
This bit of code will accept one character. If it is a not a number, it will loop back to the start, if it is a number, it will convert it to an int (from a char) and display it.
If you need more explanation or help then post here.
Code:
/* Title of project
By P Grundy
Date etc */
/* Header files */
/* --------------- */
#include <iostream.h> //for io
/* Main Program */
/* ------------ */
int main()
{
char digit;
int number;
do
{
cout<<"Enter a number or character\t";
cin>>digit;
}
while(digit<'0'||digit>'9');
number = digit-48;
cout<<"Your number is "<<number<<"\n";
return 0;
}
-
You can use iostreams built in type checking -
Code:
#include <iostream>
using namespace std;
int main()
{
int a;
cin >> a;
while(cin.fail()){
cin.clear();
cin.ignore();
cin >> a;
}
cout << a;
return 0;
}
The stream will be put in a fail state if it doesn't extract something that can be converted into an interger, whereby you can clear it and have another go at obtaining input.