简体   繁体   中英

C++ getting a character using cin.get, how to skip \n and grab only the first character?

I'm working on a school project, where a user should type in a choise for a switch/case menu. I've made an separate object to read in the menu. The program ia all about the Game of Life. I'm however struggling how to ignore all \\n's and still reading only the first character. So when the user inputs \\n \\n \\n RI like to return R, just as when then the user inputs \\n \\n RRR. However right now my code executes the command linked to R three times.

char wereld::leesoptie ( ) {    
char keuze = cin.get ( );       //So here the user will imput his \n \n RR
if (keuze == '\n') {
    while (keuze == '\n')       //I skip the \n's like this
    keuze = cin.get ( );
}                               
return keuze;                   //The returned value should be only the first real character of the string.
}//leesoptie

The code I use to execute the leesoptie function comes next:

int wereld::parameters (){
-----
keuze = leesoptie ( );
switch (keuze) {
        case 'T': case 't': return 0;
        ---
char c;
std::cin >> c;

This will read a single character ignoring any whitespaces (including newlines) by default. See for more info

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