2013-10-09 90 views
1

所以我实现了一个基于数组的列表来存储一堆(x,y)对。以下是我有为什么输入流跳过-1值?

list.h

#ifndef LIST 
#define LIST 
class list{ 
    float * values; 
    int size,last; 
public: 
    float getValue(int); 
    int getSize(); 

    void setValue(int,float); 
    bool insert(const float); 

    void resize(int); 

    list(); 
    ~list(); 
};  
#endif 

list.cpp

#include <iostream> 
#include "list.h" 

using namespace std; 

int list::getSize() 
{ 
    return size; 
} 
float list::getValue(int a) 
{ 
    if (a<size && a >=0) 
    return values[a]; 
} 
void list::setValue(int a ,float b) 
{ 
    if (a<size && a >=0) 
     values[a]=b; 
} 
bool list::insert(const float a) 
{ 
    if (a==NULL || a==EOF){ 
     return false; 
    }   
    if(last+1<size && last+1>=0) 
    { 
     values[last+1]=a; 
     last++; 
     return true; 
    } 
    else if (last+1>=size) 
    { 
     resize(size+1+((last+1)-size)); 
     values[last+1]=a; 
     last++; 
     return true; 
    } 
    return false; 

} 
void list::resize(int dim){ 
    float *temp=new float[size]; 

    for (int i=0;i<size;i++) 
     temp[i]=values[i]; 

    delete [] values; 
    values=new float [dim]; 

    for (int b=0;b<dim;b++) 
    { 
     if (b<size) 
      values[b]=temp[b]; 
     else 
      values[b]=NULL; 
    } 
    size=dim; 
    delete []temp; 
} 


list::list(){ 
    //The expected input is always >2000. 
    values=new float[2000]; 
    size=2000; 
    last=-1; 
} 
list::~list() 
{ 
    delete[]values; 
} 

的main.cpp `

#include <fstream> 
#include <iostream> 
#include "list.h" 
using namespace std; 

int main() 
{ 

ifstream file("test.txt"); 
list X,Y; 
float x,y; 
if (file) 

    { 
     while(file>>x) 
     { 
      X.insert(x); 
      file>>y; 
      Y.insert(y); 
     } 
    } 
    ofstream outfile("out.txt"); 
    for(int i=0;i<X.getSize();i++) 
     outfile<<i+1<<" "<<X.getValue(i)<<" "<<Y.getValue(i)<<endl; 

    system("notepad.exe out.txt"); 

    //system("pause"); 

    return 0; 
} 

输入流似乎跳过等于任何值为-1。我的问题是:是否有一个特定的原因,为什么-1被跳过? 另外:我知道我可以使用STL或更高效的列表,这只是为了练习。

+0

您是否尝试逐步调试代码以查看它如何处理-1? –

+0

如果您问为什么输入流正在扫描-1值,则应删除所有列表代码。你不应该显示与问题无关的代码。 – juanchopanza

+2

我的猜测是:'EOF'通常是'-1'(http://www.cplusplus.com/reference/cstdio/EOF/),所以'if(a == NULL || a == EOF){'filters '-1'。你必须用调试器来检查。 – stephan

回答

2

EOF-1most implementations,所以if (a==NULL || a==EOF){过滤-1如果这是你的执行情况。

+1

我认为值得指出的是,整个if语句是假的,应该删除。它也会跳过零。 – john

+0

@john:同意...... – stephan