I have a program that works perfectly if there is a \\n
at the end of ifstream
file.
The task was like this: Define the structure of the product ( product name , category , price , quantity in stock ) . From File trgovina.txt ( It may already contain predefined products. "Like in the picture i posted) Through functions :
The problem starts here : if the person stops writing at the first yellow marker, I would like to add a new line, so that when I want to add a new text, it will start in new line. If there is already a new line at the end of the text file, I want to just continue writing without adding new line.
The second problem is if the ofstream file has no text: in that case, I don't want to add a new line.
ofstream dat("trgovina.txt", std::ios_base::app);
if (!dat)
{
cout << "Mistake!" << endl;
return;
}
string name;
string category;
bool a = true;
double price;
int quantity;
while (a)
{
**//Here I want to check if there is a "\n" sign at the end of text
//if there isn't I want to add one, and then continue writing.
// But if the text file was empty i dont want to add new line**
cout << "enter the name of new product: ";
getline(cin, name);
dat << name << "|";
cout << "enter the category of new product: ";
getline(cin, category);
dat << category << "|";
cout << "enter the price of new product: ";
cin >> price;
dat << price << "|";
cout << "enter the quantity of new product: ";
cin >> quantity;
dat << quantity << endl; **//This works if the txt file is empty or if
//there is "\n" at the end**
cout << "more? (1 / 0)";
cin >> a;
cin.ignore();
system("cls");
};
dat.close();
Sorry for my bad english.
I got an error using
while (a)
{
trgovina.seekg(-1);
char c;
trgovina.get(c);
if (c == '\n')
{
}
else
{
dat << endl;
}
This is the picture of the txt file after running few new lines from this code. It put's a new line on the top if the file was empty, if not it works good.
Its an ofstream
so a stream in which you can only write. What you need is both reading (to determine what's inside) and write (to add items), this is called an fstream
. You can read, write and seek into a fstream
. To determine if the last char of it is a newline, just seek to the last char and read it with something like that:
fstream f("myfile.txt",std::fstream::in | std::fstream::out);
f.seekg(-1,is.f.end); // move the the end
char c;
f.get(c);
if (c=='\n') ...
else ...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.