-
Cin to textfile
I want to get artnr, artname and artpris to a textfile called varulager.txt . But I don't really remember how, can getline() send all the variables as I have written to the textfile?
Code:
void NyVara(int artnr, string artname, float artpris){
varulager.open("varulager.txt", ios::app);
if(!varulager){
cout<<"Kunde inte utföra önskad åtgärd";
}
cout<<"Artikelnummer";
cin>>artnr;
cout<<"Varubeskrivning";
cin>>artname;
cout<<"Pris (ex 99.50)";
cin>>artpris;
getline(cin, artnr, artname, artpris) >> "varulager.txt";
}
-
Nope. For writing, you would use varulager << or basic_ostream::put.
Remember that you have to output to the file you opened; not cin or cout, since they are standard stream directed to the screen by default!
-
varulager << artnr, artname, artpris; ?
-
Code:
varulager << artnr << artname << artpris;
Should work better.
Btw, I don't see where varulager is declared.
-
That's because Im writting a quite big program and this is just a function. I have it declared in the top of my program.
EDIT; Got the error message, error C2676: binary '<<' : 'class std::basic_ifstream<char,struct std::char_traits<char> >' does not define this operator or a conversion to a type acceptable to the predefined operator
Why?
-
In other words, it's global? Suggest you stay away from those. Pass it as an argument instead.
-
Since Im using the textfile in other functions I thought that was the best with a global declaration..
-
Edit: Actually, it sounds like varulager is an ifstream, you want an ofstream which does output.
And passing the fstream to the fuction by reference is preferred to using global data. In one small program it might not be a big deal, but using global data that way is generally bad practice so you might as well gain better habits now.
-
Usually you would try to avoid global variables unless they're really necessary. It's good programming practice as Daved says!