-3

I'm quite new to c++ so please understand that my question may be silly.

I need to create a function which takes from the user a table and fills it with only specific characters. Let's say that the user needs to input his name. If the user inputs a charater from A to Z (or a to z) the character should be displayed on the screen and in that case- everything is fine. The problem is- when the user inputs a forbidden character (for instance 1-9) this shouldn't be displayed on the screen and the cursor should stay in the same position).

Do you guys know how to do this?

2 Answers2

1

May be you can use this to do your job:

char ch;

while(ch = getch())
{
    if((ch>='A' && ch<='Z') || (ch>='a' && ch<='z'))
    {
        cout << ch;
    }
}

This will print only [A-Z][a-z]. You can also store your required char to use further.

Shahriar
  • 13,460
  • 8
  • 78
  • 95
1

On Windows you can use conio.h.

Also, you can overload the istream::operator>> function to make solution more elegant and easy to use:

Complete example:

#include <iostream>
#include <conio.h>

using namespace std;


struct person_t
{
    string name;
    string last_name;
};

// This is the function you're looking for.
void get_filtered_string(string &str)
{
    char c;
    str = "";

    do
    {
        c = _getch();

        if (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z'))
        {
            putchar(c); // 1
            str.push_back(c);
        }

    } while (c != '\r'); // 2

}


istream &operator>>(istream &stream, person_t &person)
{
    string str = "";

    cout << "Enter name: ";
    get_filtered_string(str);
    person.name = str;
    cout << endl;

    cout << "Enter last name: ";
    get_filtered_string(str);
    person.last_name = str;
    cout << endl;

    return stream;
}

int main()
{
    person_t person;
    cin >> person;
    cout << person.name.c_str() << " " << person.last_name.c_str() << endl;
    return 0;
}
  1. Output character to screen.

  2. In Windows when you hit Enter you're introducing two characters '\r' and '\n' in that order. Thats why we check here for '\r'.

Raydel Miranda
  • 13,825
  • 3
  • 38
  • 60