您的位置:程序门 -> c/c++ -> c++ 语言



关于《c++ primer plus》(第五版)里,std::cin的一个问题


[收藏此页] [打印本页]选择字色:背景色:字体:[][][]


关于《c++ primer plus》(第五版)里,std::cin的一个问题
发表于:2007-01-06 22:45:37 楼主
本菜鸟在看   《c++   primer   plus》(第五版)   时遇到个问题,在原书p168页里讨论的   “读取数字的循环”   里面涉及到   使用   while(cin> > array[i])来完成数字读入的判断,开始我没在意感觉简单就看得很快,到后面有章的一个编程练习时发现,用while(cin> > array[i])   这种方法判断读入尽然无效,现象是在输入符合   array[i]格式的数字时一切ok,可是输入不符合格式的字符如字母就会直接跳出程序执行,我又用《c++   primer   plus》里的例题代码,试一试可是也是无效,难度是书错了?我可是用   vs2005   和   vc++6.0   都试过的,望高手指教,谢谢。
发表于:2007-01-07 00:29:421楼 得分:0
此问题以解决   代码如下:

此程序是   c++   primer   plus   是第七节7练习题6(p221)

//   ch7_6.cpp   :   defines   the   entry   point   for   the   console   application.
//

#include   "stdafx.h "
#include   <iostream>
using   namespace   std;
const   int   le=5;

int   fill_array(double   ar[],int   be);
void   show_array(double   ar[],int   le);
void   reverse_array(double   ar[],int   le);

int   main()
{
double   ar[le];
int   count=fill_array(ar,le);
cout < <endl;
show_array(ar,count);
cout < <endl;
reverse_array(ar,count);
cout < <endl;
show_array(ar,count);
cout < <endl;
reverse_array(ar,(count-1));
cout < <endl;
show_array(ar,count);
cin.get();
cin.get();
return   0;
}

int   fill_array(double   ar[],int   le)
{
int   count=0;
cout < < "enter   double   number:   \n ";
int   i=0;
while(cin> > ar[i])
{
i++;
count++;
if(i> =le)
break;

}
cin.clear();
while(cin.get()!= '\n ')
continue;
return   count;
}

void   show_array(double   ar[],int   le)
{
for(int   i=0;i <le;i++)
cout < <ar[i] < < "   ";
}

void   reverse_array(double   ar[],int   le)
{
double   *mi=new   double[le];
if(le==0)
return;
if(le%2==0)
{
for(int   a=le/2-1,b=le/2;   b <le   ;b++,a--)
{
mi[b]=ar[b];
ar[b]=ar[a];
ar[a]=mi[b];
}
}
if(le%2==1)
{
for(int   a=le/2,b=le/2+1;   b <le   ;   b++,a--)
{
mi[b]=ar[b];
ar[b]=ar[a];
ar[a]=mi[b];
}
}
}
发表于:2007-01-08 18:10:002楼 得分:0
输入时以ctrl+z结尾就可以了


快速检索

最新资讯
热门点击