首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

C++primer plus第5版有个有关问题请问

2013-01-06 
C++primer plus第5版有个问题请教// 6.14 cingolf.cpp : Defines the entry point for the console applic

C++primer plus第5版有个问题请教
// 6.14 cingolf.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
const int Max = 5;
int _tmain(int argc, _TCHAR* argv[])
{
using namespace std;

cout << "Please enter your golf scores.\n";
cout << "You must enter " << Max << " rounds.\n";

int golf[Max];
int i;
for (i = 0; i < Max; i++)
{
cout << "round #" << i+1 << ": ";
while (!(cin >> golf[i]))
{
cin.clear();
while (cin.get() != '\n')//这行的意思谁能告诉我下,比较易懂的回复。上面的cin.clear不是已经重置了吗,这行难道是删除,重置时难道没有删除吗?不解
continue;
cout << "Please enter a number; ";
}
}

double total = 0.0;
for (int j = 0; j < Max; j++)
total += golf[j];
cout << total / Max << " = average score "
 << Max << " rounds\n";
return 0;
}


[解决办法]
首先:
cin.clear();是清除错误状态,不是清除数据。
cin.get() ;是依次读取缓冲区中的字符。
cin.ignore();是读取缓冲区中的数据,并舍弃。
其次:
当cin >> golf[i]出现错误时,错误数据依然在缓冲区中;接着调用cin.clear();清除错误状态,使得可以进行读操作;接着cin.get() != '\n'对缓冲区中的数据按字符进行读取并匹配是否读取到了回车。
[解决办法]
cin.clear()只是用来清除instream的错误位,但是输入还在,如果没有
while (cin.get() != '\n') continue;来消耗输入的话,再次进入while (!(cin >> golf[i]))的时候,还是读错误的输入,就死循环在这里了。

可以把while (cin.get() != '\n') continue;注释掉,运行时候输入abc看看有什么结果。

[解决办法]
1L说的很好了...
那个循环其实就处理下缓冲区中的'\n'...就是将字符流清理下..便于下次输入....

热点排行