Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

c++ - Switch cases and getch() don't work together

I've done a pretty simple switch where if I press a character, the integer of it adds one to itself and prints a message, it worked pretty fine with the "cin>>" and the "getchar()", but when I added the getch, It still prints the message but it stops updating the integer "how I know"? cause I made a random value that the integer has to get to, and it's between 1 and 20, and with the getch it simply goes on without stopping itself when arrived to the value

'''

void Journ(char const *bypassto = "x")
{
    int m = 4;
    
    int VAL[m];
    
    for (int j=0; j<m; j++)
    {
         VAL[j] = rand()%20 + 1;
    }
    
    char comm;
    int W;
    int A;
    int S;
    int D;  
    
    char journkey;
    if (bypassto != "x" ) {
        journkey = *bypassto;
    } else {
    
    cout << "Choose a direction: 
";
    cout <<"[FOWARD]-[LEFT]-[RIGHT]-[BACKWARDS]
";
    cout << "w for foward - a for left - d for right - s for backwards 
";

    }
    
    while (comm!=4)
    {
        // cin >> comm;
         comm = getch();
         
        switch(comm)
        {
            
            case 'w':
                {
                    cout << "You went foward. 
";
                    W++;
                    break;
                }
        
            case 'a':
                {
                    cout << "You went left. 
";
                    A++;    
                    break;
                }
            
            case 's':
                {
                    cout << "You went backwards. 
";
                    S++;
                    break;
                }
            
            case 'd':
                {
                    cout << "You went right. 
";
                    D++;
                    break;
                }
            
        }
        
        if(W == VAL[0])
        {
            BattleIntro();
            break;
        }
        
        else if(A == VAL[1])
        {
            BattleIntro();
            break;
        }
        
        else if(S == VAL[2])
        {
            BattleIntro();
            break;
        }
        
        else if(D == VAL[3])
        {
            BattleIntro();
            break;
        }
    
    }
        
} 

'''

question from:https://stackoverflow.com/questions/65882472/switch-cases-and-getch-dont-work-together

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...