2017-03-02 137 views
0

当代码运行时,FtoC()函数中的cin函数被忽略,而ctemp的值默认为0。我已经得到了代码运行期望使用其他代码(不同的循环),但我真的很想了解这种错误的机制,并得到这样做的工作。Cin不会暂停(忽略)用户输入

#include <cstdlib> 
#include <iostream> 

using namespace std; 

void threeint(); 
void FtoC(); 

int main() 
{ 
    threeint(); 
    FtoC(); 
    return 0; 
} 

void FtoC() 

{ 
    double ctemp = 0, ftemp = 0; 

    cout << "Please enter the temperature in Celsius which you would like to be\ 
      converted to Fharenheit." << endl; 

    cin >> ctemp; 

    ftemp = ((ctemp * (9/5)) + 35); 

    cout << ctemp << " degrees celsius is " << ftemp << " in fahrenheit" << endl; 
} 


void threeint() 
{ 
    int x = 0, bigint = 0, smlint = INT_MAX, avgint = 0, index = 0; 

    cout << "Input as many integers as you like and finalise by entering any 
      non-integer input" << endl; 

    while (cin >> x) 
    { 
    if (x > bigint) 
     bigint = x; 
    if (x < smlint) 
     smlint = x; 

    ++index; 
    avgint += x; 
    } 

cout << "The largest integer is " << bigint << ".\t" << "The smallest 
     integer is " << smlint << ".\t"; 

cout << "The average of all input is " << (avgint/index) << endl; 
} 
+1

如果'double'或'int'提取失败,您从不检查'cin'的状态。 –

+0

无关但是(9/5)'不会做你认为它做的事。 (提示:那个结果恰好是1,如果你感到惊讶,[见这里](http://mathworld.wolfram.com/IntegerDivision.html)) – Borgleader

回答

0

“坏读”后,您的cin处于坏输入状态。您应该跳过坏输入,并重新尝试读取

std::cin.clear(); 
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Skip bad input 
0

我会首先回答你的问题之前清除它的标志。你的cin不会等待输入的原因是因为cin没有被重置为在输入错误后接受一个新的值(比如为你的输入输入一个字母)。为了克服这个问题,你必须清除输入并忽略输入的任何错误输入。这可以通过添加下列几行程序进行:

cin.clear(); // clears cin error flags 
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // ignores any invalid input entered 

的IOS ::明确设定了流的内部错误状态标志的新值。标志的当前值被覆盖:所有位由状态中的那些代替;如果state是goodbit(它是零),所有的错误标志都被清除。

这是直接从CPlusPlus.com引用;为cin.clear()。

cin.ignore()从输入序列中提取字符并丢弃它们,直到n个字符被提取,或者一个比较等于delim。如果达到文件结束,函数也会停止提取字符。如果提前达到(在提取n个字符或查找分隔符之前),该函数将设置eofbit标志。

这是直接引自CPlusPlus.com;为cin.ignore()。

这两个引用给出了一个深入的分析,以及提供的链接,2个函数如何工作。


一对夫妇的其他事情在程序中指出的:

首先,当你做9/5,你正打算为值是1.8。但是,由于您要分割两个整数值,编译器会将最终结果保留为na int;因此,在你的代码中9/5 = 1。为了解决这个问题,你的分裂操作的divide或divisor需要是float类型的。最简单和最简单的方法是做9.0/5或9/5.0。这样,编译器就知道你想将最终结果作为浮点值。您也可以使用铸造,但是,添加小数点更容易,更简单。

其次,我不确定这个错误是否只在你已经发布的代码中,因为你说你的编译完美,但你的cout语句中的一些字符串没有用撇号,至少在你发布在这里的代码中。一个典型的例子是你的代码:

cout << "The largest integer is " << bigint << ".\t" << "The smallest 
    integer is " << smlint << ".\t"; 

上帝保佑你!