一个关于顺序表的问题,求指点

C++语言 码拜 7年前 (2017-04-26) 971次浏览
#include <iostream>
template <class _Data_Type>
class _T
{
private:
    
    int MaxSize;
    
    int _Length;
    
    _Data_Type* K;
    
public:
    _T(int _Para_Size);
    
    ~_T(){delete [] K;};
    
    bool _Creat();
};
template<class _Data_Type>
_T<_Data_Type>::_T(int _Para_Size)
{
    MaxSize=_Para_Size;
    
    K=new _Data_Type[_Para_Size];
    
    _Length=0;
}
template<class _Data_Type>
bool _T<_Data_Type>::_Creat()
{
    _Data_Type _Inpute_Ele;
    
    while (std::cin>>_Inpute_Ele&&(_Length<MaxSize))
        
    {
        
        K[_Length]=_Inpute_Ele;
        
        _Length++;
        
    }
    
    return true;
}
int main()
{
    _T<int> _a(2);
    
    _a._Creat();
    
    _T<int> _b(3);
    
    _b._Creat();
    
    return 0;
}

为什么本人创建对象_a之后就无法创建对象_b,具体创建完对象_a之后控制台直接就结束了.
bool _T<_Data_Type>::_Creat()
{
_Data_Type _Inpute_Ele;

while (std::cin>>_Inpute_Ele&&(_Length<MaxSize))  //是不是这里除了问题,本人这里设置的无效字符或ctrl+z退出破坏了CIN

//但没有在下面重置一下输入流导致创建第二个对象的时候cin还处于eofbit
//就没法输入直接退出?
{

K[_Length]=_Inpute_Ele;

_Length++;

}

return true;
}

解决方案

80

引用:
Quote: 引用:

帮你测试了可以输入,给出你输入的内容

你好,版主本人用的是xcode的编译器,代码稍作修改变成这样

#include <iostream>
#include <limits.h>
template <class _Data_Type>
class _T
{
private:
    
    int MaxSize;
    
    int _Length;
    
    _Data_Type* K;
    
public:
    _T(int _Para_Size);
    
    ~_T(){delete [] K;};
    
    bool _Creat();
};
template<class _Data_Type>
_T<_Data_Type>::_T(int _Para_Size)
{
    MaxSize=_Para_Size;
    
    K=new _Data_Type[_Para_Size];
    
    _Length=0;
    
}
template<class _Data_Type>
bool _T<_Data_Type>::_Creat()
{
    std::cout<<"Inpute _Value: ";
    
    _Data_Type _Inpute_Ele;
    
    while (_Length<MaxSize)
        
    {
        
        std::cin>>_Inpute_Ele;
        
        if (std::cin.eof()==1)
            
        {
            
            break;
            
        }
        
        else if(std::cin.fail()==1)
        {
            
            std::cout<<"The value is invaild,please Inpute again:";
            
            std::cin.clear();
            
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(),"\n");
            
            continue;
        }
        
        _Length++;
    }
    
    std::cin.clear();
    
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(),"\n");
    
    return true;
}
int main()
{
    
    _T<int> _a(4);
    
    _a._Creat();
    
    _T<int> _b(4);
    
    _b._Creat();
    
    return 0;
}

编译之后,输入1回车2回车3回车然后ctr+d(win应该是ctrl+z)结束_a然后应该可以继续输入完成_b不过本人这直接结束了

不用判断if (std::cin.eof()==1),你按ctrl+D,进入的是else if(std::cin.fail()==1),而在这个里面你应该退出循环


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明一个关于顺序表的问题,求指点
喜欢 (0)
[1034331897@qq.com]
分享 (0)