简体   繁体   中英

Only using the first character of an input to char variable

So I need this input to only use the first character of the input

cout << "\nEnter option ===> ";
cin >> selection;
selection = toupper(selection);

for example if you enter "hOttTtt" it only should look at the H.

If i don't do this it takes each letter as an input.

        default:
            cout << "\nPlease enter H,D,S,L,F, or X";
            cout << "\nEnter option ===> ";
            cin >> x;
            x = toupper(x); 

This is the part of the switch statement that runs if it is not a certain letter if that helps.

Any Help would be greatly appreciated.

If the input may contain spaces, you should be using std::getline rather than std::cin on its own. It's just good practice, even if your sole intent is to look at the first character of the input.

Anyway:

std::string selection;
std::cout << "Say something: ";
std::getline(std::cin, selection);
char fstCh = selection.at(0);

After this, fstCh will contain the first character of the input in selection . If you're using a raw char [] array instead, it's selection[0] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM