Feb 14, 2009 at 3:53pm UTC
First of all I am very new to programming, and I am sure many of my errors are basic oversights. I had a teachers help on the name section of this project, but for the life of me cant figure out the number section. I only want 30 numbers in the second string. It cant allow letters or any special characters except for enter and backspace. Any advice would be appreciated the more basic the better. Thank you.
#include <iostream>
#include <conio.h>
#include <iomanip>
#include <string>
#include <limits>
using namespace std;
#define STRLEN 30
#define STRLEN2 30
#define ENTER_KEY char(13)
#define BACKSPACE_KEY char (8)
#define pause system("pause")
#define cls system("cls")
int main () {
// Locals
char key = NULL;
int n ;
int counter = 0;
char str1 [STRLEN];
int str2 [STRLEN2];
// Enter Name:
// prompt
cout << "\n\n\n";
//cout.setf(ios::left);
cout << setw(40) << "Enter Name: ";
// input name
do {
key = getch(); // input single char
if (toupper(key) >= 65 && toupper(key) <= 91){ // check char is alpha
if (!counter) // if 1st char then make upperCase
key = toupper(key);
else
key = tolower(key);
str1[counter++] = key; // append char to cstring
cout << key;
}
} while (key != ENTER_KEY && counter < STRLEN); // exit on ENTER_KEY
str1[counter] = NULL; // set end-or-string
// output info
cls;
cout << setw(40) << "Name: " << str1 << endl;
// Enter number:
// prompt
cout <<setw(40) << "Enter a Number:"<< endl;
// input number
do {
if (n) >= 48 && (n) <= 57) {
cout << n;
}
else if n < 48 | n >57 {
cout << " \b";
}
} while (n != ENTER_KEY && counter <= STRLEN2);
str2[counter] = NULL;
// Output number
cls;
cout << setw(40) << "Number: " << str2 << endl;
std::cout << "Press ENTER to continue...";
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
return 0;
}
Feb 14, 2009 at 3:55pm UTC
As a matter of other advice, there are already functions that do some of the checking you are doing:
is_alpha() - returns whether or not char is 'a'...'z' or 'A'...'Z'
is_num() - returns whether or not char is '0'...'9'
Feb 14, 2009 at 4:01pm UTC
ok so instead of using if (toupper(key) >= 65 && toupper(key) <= 91){
use is_alpha()
and instead of n) >= 48 && (n) <= 57)'
use is_num()?