为什么此代码在字符串输入时中断?
Why is this code breaking on string input?
#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 然后如果我尝试输入一些字符串它只会打印按 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;
}
#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 然后如果我尝试输入一些字符串它只会打印按 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;
}