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

为什么无法继续读取输入?解决思路

2012-02-10 
为什么无法继续读取输入?代码如下:#includeiostream#includevectorusingnamespacestdintmain(){vecto

为什么无法继续读取输入?
代码如下:
#include   <iostream>
#include   <vector>
using   namespace   std;

int   main()
{
        vector <int>   vec1,vec2;
        int   tem;
        cin> > tem;
        while(tem)
        {
                vec1.push_back(tem);
                cin> > tem;
        }        
        cout < < "Vector1   initialized! " < <endl;
        cin.clear();//将流恢复为有效状态
        cin> > tem;
        while(tem)
        {
                vec2.push_back(tem);
                cin> > tem;
        }        
        cout < < "Vector2   initialized! " < <endl;
        size_t   n=vec1.size() <vec2.size()?vec1.size():vec2.size();
        for(vector <int> ::iterator   iter1=vec1.begin(),iter2=vec2.begin();iter1!=vec1.begin()+n;++iter1,++iter2)
        {
                if((*iter1)!=(*iter2))
                {
                        cout < < "No!!! " < <endl;
                        break;
                }        
        }        
        if(vec1.size()==vec2.size())
                cout < < "Equal! " < <endl;
        else   if(vec1.size()> vec2.size())
                cout < < "Vector2   is   the   profix   of   Vector1 " < <endl;
        else
                cout < < "Vector1   is   the   profix   of   Vector2 " < <endl;
        system( "Pause ");
        return   0;
}
问题为初始化第一个Vector之后程序就死了,不知道为什么啊???那位高手帮我解答一下!!!!

[解决办法]
试了一下你的程序: 当输入正确时(输入为int)没问题.
当输入无效时(输入字母),如你所说,程序就死了.
因此,你要加上输入有效性判断.
[解决办法]
#include <iostream>
#include <vector>
using namespace std;

int main()
{
vector <int> vec1,vec2;
int tem;
while(cin> > tem) // !!!
{
vec1.push_back(tem);
}
cout < < "Vector1 initialized! " < <endl;
cin.clear();//将流恢复为有效状态
while (cin.get() != '\n ') // !!!
{
continue;
}
while(cin> > tem) // !!!
{
vec2.push_back(tem);
}
cout < < "Vector2 initialized! " < <endl;


size_t n=vec1.size() <vec2.size()?vec1.size():vec2.size();
for(vector <int> ::iterator iter1=vec1.begin(),iter2=vec2.begin();iter1!=vec1.begin()+n;++iter1,++iter2)
{
if((*iter1)!=(*iter2))
{
cout < < "No!!! " < <endl;
break;
}
}
if(vec1.size()==vec2.size())
cout < < "Equal! " < <endl;
else if(vec1.size()> vec2.size())
cout < < "Vector2 is the profix of Vector1 " < <endl;
else
cout < < "Vector1 is the profix of Vector2 " < <endl;
system( "Pause ");
return 0;
}
[解决办法]
你的VECTOR应该有点问题:你输入的0是VECTOR中的
可是你去拿它当VECTOR的结束的判断!
我觉得应该动态的申请去初始化VECTOR!(个人意见)!

热点排行