C++ 程序似乎接受文件输入,但不打印信息
大家好,感谢所有考虑阅读的人。我最近开始学习C++的一个类,我现在正在学习文件的输入和输出。我有下面的节目,C++ 程序似乎接受文件输入,但不打印信息,c++,file-io,C++,File Io,大家好,感谢所有考虑阅读的人。我最近开始学习C++的一个类,我现在正在学习文件的输入和输出。我有下面的节目, #include <iostream> #include <vector> #include <string> #include <sstream> #include <fstream> using namespace std; class Cups{ string owner; public: s
#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;
}
}
当您在没有文件的情况下编译时,程序会输出警告,但是在运行时,它会输出警告
Natassa, Grande
2
Demy, Tall
1.5
Elena, Short
1
, Short
1
我试着在gdbonline中运行它,我的提取可能有问题,但我无法解决。感谢所有费心阅读的人,更要感谢所有帮助过你的人
编辑:在infle.eof()检查中添加了not符号,但仍然得到上面显示的重影线。我想发布到codereview,但这段代码仍然不能正常工作。你说的“无文件编译”是什么意思?你不是说“运行时不使用文件作为参数”吗?然后,
while(infle.eof())
似乎使用了错误的停止条件。无论如何,在阅读之前检查EOF是错误的,你应该可以在这里找到很多解释。还有三件事:一旦运行,请在codereview.stackexchange.com上提交代码。作为这里的新用户,请进一步阅读。@UlrichEckhardt噢,感谢那个人!
Natassa, Grande
2
Demy, Tall
1.5
Elena, Short
1
, Short
1