I want to write a little program which should be used in supermarkets. everything is fictitious and it’s only for learning purposes.
However, The tool generate a new data for every new article. in the data there are 2 lines, the name and the prise.
The data is named as the article number of the product. So the user enter a articlenumber and the tool looks for a data with this number, if it found it, it reads the 2 lines and initiates the variables.
But for some reasons it does not convert and copy the strings correctly.
here is the part which loads the data.
int ware::load()
{
string inhalt;
cout << "please insert article number" << endl;
cin >> articlenumber;
productname.open(articlenumber, ios::in);
if (!productname.is_open())
{
cout << "can't find the product." << endl;
return 1;
}
if (productname.is_open())
{
while (!productname.eof())
{
getline(productname, inhalt);
strcpy(name,inhalt.c_str());
getline(productname, inhalt);
price = atoi (inhalt.c_str());
cout << inhalt << endl;
}
warenname.close();
}
cout << endl << endl <<
"number: " << inhalt <<
" preis: " << price <<
" name: " << name <<
endl << endl; //this is a test and will be deleted in the final
}
hope you can help me!
Here is the class:
class ware{
private:
char articlenumber[9];
char name[20];
int price;
fstream warennamefstream;
ifstream warenname;
public:
void newarticle(); //this to make a new product.
void scan(); //this to 'scan' a product (entering the article number ;D)
void output(); //later to output a bill
int load(); //load the datas.
};
hope everything is fine now.
First, you have a
using namespace std;somewhere in your code. This occasionally leads to subtle bugs. Delete it. ( Using std Namespace )The type of
articlenumberis incorrect. Declare itstd::string, notchar[]. ( What is a buffer overflow and how do I cause one? )There is no reason to have an
ifstreamlying around waiting to be used. Also, there is no point in providingios::in— it is the default. Just use the one-argument form of theifstreamconstructor.Don’t bother checking to see if the file opened. Your users don’t care if the file was present or not, they care whether the file was present AND you retrieved the essential data.
This loop is just wrong.
eof(). It doesn’t do what you think it does, and will cause bugs.close. Just let the file close when theistreamgoes out of scope.warenamedifferent thanproductname?char[]. This is the 21st century. Usestd::string..
endlwhen you mean to say'\n'. Each of thoseendlmanipulators invokesflush, which can be very expensive. ( What is the C++ iostream endl fiasco? )returna value.Try this instead: