首页 > 解决方案 > 为什么这段代码在字符串输入时会中断?

问题描述

#include <iostream>

using namespace std;
string flip();
int x;


int main()
{
    for(int i=0;i<10;++i){
    cout<<"Press 1 and enter"<<endl;
    cin>>x;
    if(isalpha(x)==true){
            cout<<"int pls"<<endl;


    }
    else if(x==1){
        flip();
        cout<<"flipped"<<endl;


    }

    else if(x!=1){
        cout<<"try again"<<endl;
    }


    }
    system("pause>0");
    return 0;

}
string flip(){
    string ans;
    int y=rand()%2;
    if(y==0){
        string ans = "Heads";
            cout<<ans<<endl;
    }
    else{
       string ans = "Tails";
     cout<<ans<<endl;
    }

    return ans;

}

每当我输入 2 而不是 1 时,它会起作用并说再试一次,但是当我写一些像“fa”这样的字符串时,如果我将 x 更改为 int 并且如果我尝试输入一些字符串,它只会打印 press 1 并输入 10 次,而不是再次要求输入

标签: c++14

解决方案


变量 'x'(=isalpha() 的参数) 的类型必须是 char。如果 'x' 的类型是整数,则函数 (=isalpha()) 将 'x' 识别为 ASCII 值。试试这个代码怎么样?

char x;


int main()
{
    for(int i=0;i<10;++i){
        cout<<"Press 1 and enter"<<endl;
        cin>>x;
        if((bool)isalpha(x)==true){
            cout<<"int pls"<<endl;
        }
        else if(x=='1'){
            flip();
            cout<<"flipped"<<endl;
        }
        else {
            cout<<"try again"<<endl;
        }
    }
    system("pause>0");
    return 0;
}

推荐阅读