Hello and thanks to all who considered reading. I recently started learning c++ in a class and I am just now learning file input and output. I have the following program,
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <fstream>
using namespace std;
class Cups{
string owner;
public:
string type;
float size;
Cups(string owner, string type, float size){
this->owner = owner;
this->type = type;
this->size = size;
}
string get_owner(){
return owner;
}
};
vector<Cups> extract(string filename){
ifstream inFile;
string line;
string owner, type;
float size;
vector<Cups> o;
inFile.open(filename);
if(!inFile.is_open()){
cout<<"Error, file not found..."<<endl;
exit(1);
}
while(!inFile.eof()){
getline(inFile, line);
stringstream ss(line);
getline(ss, owner, ',');
getline(ss, type);
if(type.compare("Short")==0){
size = 1.0;
}
else if(type.compare("Tall")==0){
size = 1.5;
}
else if(type.compare("Grande")==0){
size = 2.0;
}
else if(type.compare("Venti")==0){
size = 2.5;
}
else{
cout<<"Error, "<<owner<<"'s cup size not found."<<endl;
exit(1);
}
o.push_back(Cups(owner, type, size));
}
inFile.close();
return o;
}
int main(int argc, char** argv){
if(argc < 2){
cout<<"Please compile with and orders file."<<endl;
exit(1);
}
int i;
vector<Cups> orders = extract(argv[1]);
for(i = 0; i < orders.size(); i++){
cout<<orders[i].get_owner()<<", "<<orders[i].type<<endl;
cout<<orders[i].size<<endl;
}
}
with the following file, input as an executable argument
Natassa,Grande
Demy,Tall
Elena,Short
The program outputs the warning when you compile without a file just fine, however when running it, it outputs
Natassa, Grande
2
Demy, Tall
1.5
Elena, Short
1
, Short
1
I've tried running it in gdbonline and there seems to be a problem with my extraction perhaps, but I can't figure it out. Thanks for all who bothered to read and a bigger thanks to any who help.
Edit: Added the not symbol ot the inFile.eof() check, but still getting the ghost line shown above. I would post to codereview but this code is still not working correctly.
while(inFile.eof())
seems to use the wrong stop condition. In any case, checking for EOF before trying to read something is wrong, you should be able to find lots of explanations here. Three more things: Once you have it running, submit your code at codereview.stackexchange.com. As a new user here, further take the tour and read How to Ask. – Ulrich Eckhardt Sep 30 '20 at 18:20