所以我實現了一個基於數組的列表來存儲一堆(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或更高效的列表,這只是爲了練習。
您是否嘗試逐步調試代碼以查看它如何處理-1? –
如果您問爲什麼輸入流正在掃描-1值,則應刪除所有列表代碼。你不應該顯示與問題無關的代碼。 – juanchopanza
我的猜測是:'EOF'通常是'-1'(http://www.cplusplus.com/reference/cstdio/EOF/),所以'if(a == NULL || a == EOF){'filters '-1'。你必須用調試器來檢查。 – stephan