【问题标题】:Why is this code breaking on string input?为什么这段代码在字符串输入时会中断?
【发布时间】:2021-09-06 06:18:48
【问题描述】:
#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


    【解决方案1】:

    变量'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;
    }
    

    【讨论】:

      猜你喜欢
      • 2014-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多