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

一个菜鸟的C++有关问题

2012-03-08 
一个初学者的C++问题我最近用VisualC++6.0写C++,只是写些小程序,比如for(number++){cout PleaseEnter

一个初学者的C++问题
我最近用Visual   C++   6.0写C++,只是写些小程序,比如
for(;;number++)
{cout   < <   "Please   Enter   the   score   (   \ "0\ "   to   end)   :   ";
cin   > >   score;
if   (score   !=   0)
total   +=   score;
else   break;
}

这样的.

发现一些定义成int   的数据,如果键盘输入的是非数字的字符,DOS的运行窗口就会发生刷屏..不知是为什么?如何在编程时避免这样的问题?

小生在此先谢谢啦~~

[解决办法]
打错了。“偶坚持认为这是大多数编译器的bug”。
严格讲是库实现的bug。
[解决办法]
循环体内加入
cin.ignore();
cin.clear();
或者fflush(stdin);//需要头文件stdio.h
清空缓冲区

导致刷屏的原因是非数字字符无法被cin接收
一直停留在缓冲区,导致下一次cin时直接从缓存读数
但字符无法读取结果导致无限循环
[解决办法]
try this:

int i;
while(1)
{
cout < < "input an integer: ";
if(cin > > i) break;
cout < < "error: not an integer\n ";
cin.clear();
cin.ignore(numeric_limits <int> ::max(), '\n ');
}
cout < < i < < endl;

[解决办法]
#include <iostream>
#include <limits>
using namespace std;

int main() {
int score = 0;
int total = 0;
for(;;) {
cout < < "Please Enter the score ( \ "0\ " to end) : ";
cin > > score;
if(!cin.good()) {
cout < < "Bad input, input again. " < < endl;
cin.clear();
cin.ignore(numeric_limits <int> ::max(), '\n ');
//或fflush(stdin);
continue;
}

if (score != 0)
total += score;
else
break;
}

cout < < "Total = " < < total < < endl;
return 0;
}
[解决办法]
//想到一个笨方法:
//用char acception[ 20 ]接收输入值,然后检查接收到的字符是否在(48-57)之间,
//也就是0-9之间,再转化成int
//可是用空格连续输入时虽然能得到结果,但输出格式不好看。
#include < iostream >
#include < cmath >

using namespace std;

int main()
{
int score = 0, l, total = 0;
char acception[ 20 ];

do
{
score = 0;
cout < < "Please Enter the score ( \ "0\ " to end) : ";
cin > > acception;
l = ( int )strlen( acception );
for( int i = 0; i < l; i++ )
{
if( acception[ i ] > = 48 && acception[ i ] <= 57 )
{
score = score + ( ( int )acception[ i ] - 48 ) *
( ( int )pow( 10, ( l - 1 - i ) ) );
}
else
{
cout < < "This is not a standard score, enter again:\n ";
break;
}
}
total = total + score;
}while( acception[ 0 ] != 48 );
cout < < "total = " < < total < < endl;

system( "pause " );
return 0;
}
[解决办法]
cin.good();
cin.fail();
看你输入的是否是整数


[解决办法]
楼主试试boost::lexical_cast

#include <iostream>


#include <boost/lexical_cast.hpp>
using namespace std;
int main()
{
int x;

while(1){
string str;
cin > > str;
try {
x = boost::lexical_cast <int> (str);
break;
} catch (boost::bad_lexical_cast& ) { }
}

cout < < x < < endl;
system( "pause ");
return 0;
}

热点排行