Reputation: 1193
I have two functions one that saves content of my array to a textfile and a function that reads the same into the array. Everything was written in VS and now I'm trying to make a GUI to my app. My save to file function works like a charm but when I try to read that file in QT with my read function nothing happens. Do I have to rewrite the function for it to work in QT? if not what could be the problem? What can i "throw" if in.fail()?
void DH::read()
{
ifstream in("text.txt");
string strKcal=" ";
int kcal=0;
string strCarb=" ";
double carb=0.0;
string strProtein=" ";
double protein=0.0;
string strLipid=" ";
double lipid=0.0;
string name;
string usrName;
string usrName1;
string usrName2;
string date;
string nrs;
getline(in,nrs);
this->nrOfDiets=atoi(nrs.c_str());
if(!in.fail())
{
for(int i=0;i<this->nrOfDiets && in.good();i++)
{
getline(in,usrName1,' ');
getline(in,usrName2);
usrName=usrName1+ " " + usrName2;
getline(in,date);
getline(in,name,'\t');
getline(in,strKcal,'\t');
getline(in,strCarb,'\t');
getline(in,strProtein,'\t');
getline(in,strLipid);
kcal=atoi(strKcal.c_str());
carb=atoi(strCarb.c_str());
protein=atoi(strProtein.c_str());
lipid=atoi(strLipid.c_str());
this->dh[i]=new Diet(name,kcal,protein,carb,lipid,usrName,date);
}
}
else
//cout<<"Error!"<<endl;
in.close();
}
I know I could've used in>> instead of getline all the time, but for some reason it didn't work :S
Upvotes: 1
Views: 164
Reputation: 3870
Generally, no, you shouldn't need to do anything differently to make correct code work as part of a Qt application. I haven't studied your code in detail, but it seems fine at a glance at least.
However, there are some things that will be different. First of all, control in graphical programs is usually inside out from command line programs. You're not going to be writing the program flow explicitly. Instead, you'll be reacting to events (button clicks, menu selections, etc.). Second, you're typically running them via some different launch method (clicking an icon or running it from the IDE) that can change things like the current working directory of the program.
Without more information, we can't tell you what your problem is. But I'd check that the program is actually running from a directory where the relative path "text.txt" refers to a valid file. Also, and this may sound crazy, but verify that your code is actually being called.
On a side note, your last sentence about operator>> vs. getline...sometimes it's fine to just move on to something that works, but you'd probably be well served to spend the time to figure things like this out when you can. Learning why something doesn't do what you thought it would can often save you a huge amount of time and frustration later.
Upvotes: 1