c++14 - 为什么这段代码在字符串输入时会中断?
问题描述
#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 次,而不是再次要求输入
解决方案
变量 '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;
}
推荐阅读
- angularjs - 自定义指令抛出 -- 错误:$compile:ctreq Missing Required Controller
- node.js - RPi3 / Ubuntu Mate 16.04 上的 Node-Red-Dashboard UI_Gauge 不会随有效负载而变化
- azure - 是否有任何 azure API App cmdlet?
- acumatica - 将默认值从一个网格设置为同一屏幕中的另一个网格
- ios - 在不同的视图控制器中打开 webkit 视图
- java - 单元测试时未找到自定义注释
- python - 如何在直接索引列表时使用for循环和upper()将列表中的所有元素转换为大写?
- javascript - 如何在 JQuery 中为每个循环制作可变延迟/睡眠
- reactjs - 将语言添加到 Handsontable 反应
- javascript - 更新文档时的 pouchDB query() 错误