C ++:检查非数字输入和分配给double [英] C++: Checking for non-numeric input and assigning to a double

查看:168
本文介绍了C ++:检查非数字输入和分配给double的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是我现在的代码:

char ch;
int sum = 0;
double values[10];
int i = 0;
cin >> ch;
    while (!isalpha(ch))
    {  
        values[i] = ch; 
        sum += values[i]; 
        i++;  
        cin >> ch;
    }

发生的是,如果我输入值1, ch作为char。现在ch将它的值赋值为double,并进行隐式转换。因此,它将ASCII值1分配给值[i]。我想它只是分配1到值[i]。有没有更好的方法来做到这一点?

What is happening is that if I enter the value 1, that gets assigned to ch as a char. Now ch is assigning it's value to a double and doing an implicit cast. So it is assigning the ASCII value of '1' to values[i]. I want it to just assign 1 to values[i]. Is there a better way to do this? Or is there something that I'm missing?

推荐答案

如果要将数字字符转换为相应的数字值,可以简单地从中减去'0'

If you want to convert a digit character to its corresponding digit value, you can simply subtract '0' from it:

char ch = '2';
int value = ch - '0'; // value is 2

但是,读取浮点数的最好方法是提取 double s cin

However, the best way to read in floating point numbers is just to extract doubles from cin:

double value = 0;
if (cin >> value)
{
    // value is good
}
else
{
    // invalid value was entered; handle the error appropriately
}

请注意,如果提取失败,从流中,您将需要调用 cin.clear()来清除流的失败状态,您可能需要调用 cin.ignore ()忽略任何尾随字符(例如,如果您使用基于行的输入,则需要忽略所有内容,直到下一个换行符为止)。

Note that if the extraction fails and you want to continue reading from the stream, you will need to call cin.clear() to clear the fail state of the stream and you may need to call cin.ignore() to ignore any trailing characters (for example, if you are using line-based input, you'll need to ignore everything until the next newline).

这篇关于C ++:检查非数字输入和分配给double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆