不包括非整数输入

  • 本文关键字:整数 不包括 c++ cin
  • 更新时间 :
  • 英文 :


S是正整数且>= 5时,我正在尝试输出"Rose"。然而,当我输入5.1时,输出仍然是"Rose"。我想不通:([编辑:我忘了说S是一个奇数正数,这就是为什么我在代码中包含S%2 == 1]

#include <iostream>
using namespace std;
int main()
{
int S;
cout << "Please input the size of a rose: " << endl;
cin >> S;
if (S%2 == 1 && S >= 5 && sizeof(S) == 4) {
cout << "Rose" << endl;
}
else {
cout << "Invalid input size!" << endl;
}
}

S具有"int"类型,因此当您输入5.1时,只有5会被读取到S中。一种解决方案是将S1读取为双精度(或字符串等(,并检查它是否表示整数。如果是,则将它们转换为int并存储在S中,否则打印错误消息。