Home > other >  function CIN gets skipped every time
function CIN gets skipped every time

Time:01-11

I wanted to make a small "game" with a little bit of story, but I did some code and I think i did some major mistakes, here's the code

int main() {
char o, z, q, r;
string f, w = "yes", e = "no";

cout << "Hello, summoner!" << endl;
cin >> o;

cout << "You know why you are here, right?" << endl;
cin >> q;

switch ( z ) {

case 'w':
    cout << "Ok";
    break;

case 'e':
    cout << "You are here to fight for your life!";
    break;

    }
return 0;
}

The second cin, the cin >> q; gets skipped every time I run the code and I don't know what to do.

CodePudding user response:

It may not get skipped. You may be entering more than one characters in 'o', which is not allowed in your case and the second character automatically is stored in variable q. Try changing the data type of the variables mentioned if you want to enter longer strings in the variables.

CodePudding user response:

The second cin does not get skipped! When you enter "Hi" then std::cin >> o; will read 'H' while 'i' is still left in the stream. Then std::cin >> q; will read that 'i'. You can see the effect here:

#include <iostream>

int main() {
    char first,second;
    std::cin >> first;
    std::cin >> second;
    std::cout << first << " " << second;
}

When you type Hi then press enter the output will be

H i

If you want to store more than a single character then do not use char. For elaborated input checking you can use std::getline to read the whole line of user input and then check if it was a single character, a whole word, or something else.

PS: Don't use single letter variable names only. This is confusing and makes your code very hard to read and understand.

PPS: No offense, but don't make assumptions on what your code does. Instead use a debugger to see what actually happens. And try to be more precise on what you provide as input and what happens then. Your interpretation of "cin gets skipped" is off, and you could have seen this by inspecting the values of o and q after both cins.

  •  Tags:  
  • Related