1、判断是整数还是字符:通过int n = scanf("%d",&a); 判断n的值,然后,如果要继续输入,用flush()函数,清晰缓冲区,再次输入。
1.1、对于C++来说,使用cin输入,如果cin输入出错,会返回false, 然后,使用cin.clear()函数清空缓存区,继续输入。clear() 类似C中的flush。
2、判断整数还是小数:定义接收内容的字符串string s,调用C++的getline方法,格式如下:getline(cin,s),getline可以接收空格,遇到换行输入结束。然后依次判断字符串中的字符,是否为数字,如果遇到一个非数字的字符,则不是整数。
void test()
{
string str1;
cin >> str1;
for (size_t i = 0; i < str1.size(); i++)
{
switch (str1.at(i))
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': break;
default: cout << "有小数" << endl;
break;
}
}
}
最后,一般判断之后需要转换为原来的样子:使用自带的字符数组转换方式:
// array to integer
to_price=atoi(price.c_str());
// 类似还有atof atol atoll
// 反转 to_string()
整数变成字符串直接使用to_string(int val);
但是,float a=25.3, 使用to_string(a), 之后输出的字符串a为25.299999;
float a=25.4, 之后输出的字符串a为25.400000;
so:
(1) 注意小数转换为字符时,加上的0000;
(2) 注意小说后为奇数的数据丢失情况。
// 控制字符串显示的长度
cout.write(str.c_str(), 5);
// 或者使用double modf(integer , fptr)函数
<math.h>
double modf(double x,double * ip)
把x分成整数和小数两部分,两部分正负与x相同,函数返回小数部分,整数部分保存在ip中
函数名: modf
功 能: 把数分为整数和小数 (The modf function breaks down the floating-point value x into fractional and integer parts, each of which has the same sign as x. The signed fractional portion of x is returned. The integer portion is stored as a floating-point value at intptr.
)
用 法: double modf(double x, double *intptr);
程序例:
#include <math.h>
#include <stdio.h>
int main(void)
{
double fraction, integer;
double number = 100000.567;
fraction = modf(number, &integer);
printf("The whole and fractional parts of %lf are %lf and %lf\n",
number, integer, fraction);
return 0;
}
本文介绍如何在C++中判断输入是整数、小数还是字符,使用cin和getline方法进行输入错误处理及数据类型判断。同时,讲解了如何将字符串转换为整数、浮点数,并讨论了转换过程中的精度问题。

607

被折叠的 条评论
为什么被折叠?



