Ahmed Mohamed
Ahmed Mohamed

Reputation: 13

How to ignore all characters except first character?

#include <iostream>    
using namespace std;

int main ()
{
    char letter;
    while (cin>>letter)
    {
        switch (letter)
        {
            case 'a':
                cout<<"ant"<<endl;
                break;
            default :
                cout <<"enter only lower cases letters "<<endl;
        }
    }
    return 0;
}

Is there any feature of c++ that ignores the characters next to first character? Because i.e., if I enter aaa it displays ant ant ant, so I want to get rid of this part. I hope you get my question.

Upvotes: 0

Views: 837

Answers (4)

Justin Randall
Justin Randall

Reputation: 2278

You can treat the user input as a std::string and then just look at the first character from it for your switch statement. This will ignore anything the user inputs after the first character. I can't imagine the use case for this, but I believe this is what you're asking for.

#include <cstdlib>
#include <iostream>

int main( int argc, char *argv[] )
{
    std::string word;
    while (std::cin >> word)
    {
        char letter = word[0];
        switch (letter)
        {
            case 'a':
                std::cout << "ant" << std::endl;
                break;
            default:
                std::cout << "please enter only lower case letters" << std::endl;
                break;
        }
    }
    return EXIT_SUCCESS;
}

Upvotes: 1

drew767
drew767

Reputation: 31

Only first char will be saved

int main()
{
    char c = 0;
    c = getchar();
    putchar(c);
    return 0;
}

Upvotes: 0

UKMonkey
UKMonkey

Reputation: 6993

Read chars repeatedly and keep track of what's been added

#include <set>

int main () {
    char letter;
    std::set<char> used;
    while (cin >> letter) {
        if (!used.insert(letter)[1])   // note returns a pair; 2nd item ([1]) is true if it didn't exist before
            continue;
        switch (letter) {
        case 'a':
            cout << "ant" << endl;
            break;
        default:
            cout << "enter only lower cases letters " << endl;
            break;
        }
    }
    return 0;
}

Upvotes: 0

john
john

Reputation: 87952

Read a string and then switch on the first character. Like this.

int main () {
    string word;
    while (cin >> word) {
        switch (word[0]) {
        case 'a':
            cout << "ant" << endl;
            break;
        default:
            cout << "enter only lower cases letters " << endl;
            break;
        }
    }
    return 0;
}

Upvotes: 4

Related Questions