How to create multiple file in fstream with loop [duplicate] - c++

This question already has answers here:
How to concatenate a std::string and an int
(25 answers)
Closed 2 years ago.
I am new in coding and in this community I want to save multiple student info in multiple file in ".txt" file like "student1.txt", "student2.txt", "student3.txt" etc. See my code then I hope you will understand my problem.
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main() {
for(int i = 1; i < 30; i++) {
string name, roll, gpa;
cout << "Enter student info";
cout << "name :";
cin >> name;
cout << "\nEnter Roll :";
cin >> roll;
cout << "\nEnter gpa :";
cin >> gpa;
ofstream file;
/* Problem part :I know this part of code will never work */
file.open("Student <<i<<".txt");
/* what should I do */
file << name << endl << roll << endl << gpa;
file.close();
}
}

Here is what I think you need: std::to_string and operator+ (string)
Check out the answers on this thread. There they have shown numerous methods to do this.
Code:
#include <fstream>
#include <iostream>
#include <string>
int main() {
for (int i = 1; i < 30; i++) {
std::string name, roll, gpa;
std::cout << "Enter student info : " << std::endl;
std::cout << "Name : ";
std::cin >> name;
std::cout << "Enter roll number : ";
std::cin >> roll;
std::cout << "Enter GPA : ";
std::cin >> gpa;
std::ofstream file("Student" + std::to_string(i) + ".txt");
file << name << std::endl
<< roll << std::endl
<< gpa << std::endl;
}
}

Related

How to add getline in c++?

I am looking to remove the space from the name part of my assignment which allows users to put any name with or without space in my product list. for example "TV stand", I assume getline function will help me with it but I couldn't add the getline function into my main. can anyone help me with it?
#include <bits/stdc++.h>
#include <iostream>
#include <string>
using namespace std;
struct product {
char product_name;
int no_of_purchase;
int no_of_sales;
double purchase_cost;
double selling_price;
double profit_loss;
double percent_profit_loss;
string product_sales;
};
bool Compare(product P1, product P2)
{
return P1.percent_profit_loss > P2.percent_profit_loss;
}
int main()
{
int n;
cout << "Enter the number of the product:";
cin >> n;
cout << "\n";
product Products[n];
for (int i = 0; i < n; ++i) {
cout << "Enter the name of the product: ";
cin >> Products[i].product_name;
cout << "Enter the number of " << Products[i].product_name << " purchased: ";
cin >> Products[i].no_of_purchase;
cout << "Enter the number of " << Products[i].product_name << " sold: ";
cin >> Products[i].no_of_sales;
To be honest I don't understand your question but this might be helpful for you
I changed the product_name data type from char to string because the char data type is not making any sense
#include <iostream>
#include <string>
using namespace std;
struct product {
string product_name;
int no_of_purchase;
int no_of_sales;
double purchase_cost;
double selling_price;
double profit_loss;
double percent_profit_loss;
string product_sales;
};
bool Compare(product P1, product P2)
{
return P1.percent_profit_loss > P2.percent_profit_loss;
}
int main()
{
int n;
cout << "Enter the number of the product:";
cin >> n;
cin.ignore();
cout << "\n";
product Products[n];
for (int i = 0; i < n; ++i) {
cout << "Enter the name of the product: ";
getline(cin, Products[i].product_name);
cout << "Enter the number of " << Products[i].product_name << " purchased: ";
cin >> Products[i].no_of_purchase;
cout << "Enter the number of " << Products[i].product_name << " sold: ";
getline(cin, Products[i].no_of_sales);
cin.ignore();
}
return 0;
}

How do I add vectors into my structs to create an inventory system in which I can add multiple different wines to the system using only one struct?

I have a school assignment in which I have to create a Wine Inventory System where the user can add multiple different wines without a finite number I assume.
I need to create vectors but I'm not sure. I don't know what to try.
#include <string>
#include <iostream>
#include <vector>
using namespace std;
struct Wine1
{ //struct for Wine pssibly needs Vector
string name;
string year;
string place;
string price;
} wine;
void printwine(Wine1 wine);
int main()
{
string str; //input for data
cout << "Please enter the data of the First wine: " << endl;
cout << "Enter name: ";
getline(cin, wine.name);
cout << endl << "Enter year: ";
getline(cin, wine.year);
cout << endl << "enter country of creation: ";
getline(cin, wine.place);
cout << endl << "enter price: ";
getline(cin, wine.price);
cout << endl;
cout << "your entered data: " << endl;
printwine(wine);
cout << endl;
printwine2(wine2);
cout << endl;
printwine3(wine3);
}
void printwine(Wine1 wine)
{ //data the user typed as output
cout << "Wine1" << endl;
cout << "the name is: " << wine.name << endl;
cout << "it's year is: " << wine.year << endl;;
cout << "its country of creation is: " << wine.place << endl;;
cout << "it's price is: " << wine.price << endl;
}
It should output the name of the wine, the year, it's country, and it's price, for each wine which was added.
A good starting should be using vector of Wine1.
std::vector<Wine1> wineVec;
wineVec.reserve(/*size*/) // reserve the memory if you know the number of wines beforehand
The printwine function should now take std::vector<Wine1>(preferably const-reference as the data is read-only) and iterate through the vector to print the attributes of the Wine1.
Something like:
#include <string>
#include <iostream>
#include <vector>
void printwine(const std::vector<Wine1>& vecWine)
{
for (const auto& wine : vecWine)
{
// do printing each: wine.name, wine.year,... so on
}
}
int main()
{
std::vector<Wine1> vecWine;
int wineNumber = 2;
vecWine.reserve(wineNumber);
std::string name, year, place, price;
for (int i = 0; i < wineNumber; ++i)
{
// get the user input for name, year, place, and price
std::cin >> name >> year >> place >> price;
vecWine.emplace_back(Wine1{ name, year, place, price });
}
printwine(vecWine);
}
That said, you should read more about std::vector
to get to know more, how it works.
Also, good to read about, how to overload operator>> and operator<<, so that you could even write code, much simpler.
Following is an incomplete code, which I leave you to complete after covering the topics which I mentioned.
void printwine(const std::vector<Wine1>& vecWine)
{
for (const auto& wine : vecWine)
{
std::cout << wine << '\n';
}
}
int main()
{
std::vector<Wine1> vecWine(wineNumber);
for (Wine1& wine : vecWine)
{
std::cin >> wine;
}
printwine(vecWine);
}
I believe there is a misunderstanding: you do not intend your struct Wine1 to contain a vector but instead, you want a vector of Wine1's.
I suggest a data structure similar to the following:
struct Wine {
string name;
string year;
string place;
string price;
};
void printwinelist(vector<Wine>& list){
for(Wine& w : list){
printwine(w);
}
}
vector<Wine> winelist;
The main method has to be rewritten accordingly, to append additional objects to the vector.
While I could rewrite your code accordingly I suspect, that a better next step for you would be to read up on some of the concepts used, such as vectors.
You probably want something like this:
#include <string>
#include <iostream>
#include <vector>
using namespace std;
struct Wine1
{ //struct for Wine pssibly needs Vector
string name;
string year;
string place;
string price;
};
void printwine(Wine1 wine);
int main()
{
vector<Wine1> wineinventory;
// read 3 wines
for (int i = 3; i < 10; i++)
{
Wine1 wine;
string str; //input for data
cout << "Please enter the data of the First wine: " << endl;
cout << "Enter name: ";
getline(cin, wine.name);
cout << endl << "Enter year: ";
getline(cin, wine.year);
cout << endl << "enter country of creation: ";
getline(cin, wine.place);
cout << endl << "enter price: ";
getline(cin, wine.price);
cout << endl;
cout << "your entered data: " << endl;
printwine(wine);
wineinventory.push_back(wine); // store in vectore
}
// print all wines in the vector
for (int i = 0; i < wineinventory.size(); i++)
{
cout << "Wine " << i << ":" endl;
printwine(wineinventory[i]);
}
}
Disclaimer: this is untested code, I'm not even sure if it compiles, but you should get the idea.
There is still much room for improvement.

Unreadable output file, is this a fault?

Here is my code:
#include <stdio.h>
#include <iostream>
#include <conio.h>
char filename[100];
FILE *stream, *stream2;
char s[20];
struct date
{
int day, month, year;
};
struct employee
{
int ID;
char name[100];
date birthdate;
char address[20];
char rank[20];
int money;
};
void main()
{
errno_t err;
// Open for read (will fail if file "crt_fopen_s.c" does not exist)
// Open for write
err = fopen_s(&stream2, "C:/Users/Van/Desktop/LAALAL/fool.txt", "w+");
if (err == 0)
{
employee nv;
std::cout << "\nInput information of an employee:\n";
std::cout << "\tInput ID : ";
std::cin >> nv.ID;
std::cin.sync();
std::cout << "\tInput name : ";
std::cin.clear();
gets_s(s);
gets_s(nv.name);
std::cout << "\tInput birthdate (Day Month Year ) : ";
std::cin >> nv.birthdate.day >> nv.birthdate.month >> nv.birthdate.year;
std::cout << "\tInput address: ";
std::cin.clear();
gets_s(s);
gets_s(nv.address);
std::cout << "\tInput rank : ";
std::cin.clear();
gets_s(s);
gets_s(nv.rank);
std::cout << "\tMoney : ";
std::cin >> nv.money;
std::cin.sync();
std::fwrite(&nv, sizeof(nv), 1, stream2);
std::fclose(stream2);
}
}
Well I don't have any problem with the code, but when I input my information, I cant read the output in the file. Here is the picture of my output:
What is my problem?
Thanks in advance for your time!
You are using fwrite() function, which writes data to files as binary, not as text (ASCII). You should be using std::ofstream class from <fstream> (instead of FILE), together with << operator.
More info here:
http://www.cplusplus.com/doc/tutorial/files/
Example code:
#include <iostream>
#include <fstream>
using namespace std;
struct some_struct{
int some_int;
char some_char;
};
int main () {
struct some_struct x;
x.some_int = 123123;
x.some_char = 'x';
//This is how you open the file.
ofstream myfile;
myfile.open ("example.txt");
//This is is how you write to it.
myfile << "Integer: " << x.some_int << " Char: " << x.some_char;
//This is how you close it.
myfile.close();
return 0;
}
Output inside the file example.txt:
Integer: 123123 Char: x
You can use fstream library to programming by operators like << or >>
#include <iostream>
#include <fstream>
using namespace std;
struct date
{
int day, month, year;
};
struct employee
{
int ID;
char name[100];
date birthdate;
char address[20];
char rank[20];
int money;
};
int main()
{
char ch;
ofstream file("fool.txt");
if (!file)
{
cout << ""Cannot open file, press any key to continue ...";
cin.get();
exit(0);
}
employee nv;
cout << "\nInput information of an employee:\n";
cout << "\tInput ID : ";
cin >> nv.ID;
cin.ignore();
cout << "\tInput name : ";
gets_s(nv.name);
cout << "\tInput birthdate (Day Month Year) : ";
cin >> nv.birthdate.day >> nv.birthdate.month >> nv.birthdate.year;
cin.ignore();
cout << "\tInput address: ";
gets_s(nv.address);
cout << "\tInput rank: ";
gets_s(nv.rank);
cout << "\tMoney: ";
cin >> nv.money;
cin.ignore();
file << nv.ID << ' ' << nv.name << ' ' << nv.birthdate.day
<< ' ' << nv.birthdate.month << ' ' << nv.birthdate.year
<< ' ' << nv.address << ' ' << nv.rank << ' ' << nv.money << ' ';
file.close();
cout << "\nOutput From File : \n";
ifstream file2("fool.txt");
file2.get(ch);
while (!file2.eof())
{
cout.put(ch);
file2.get(ch);
}
file2.close();
cout << "\nOutput Completed";
cin.get();
}
and pay attention to these hints :
Declare the usage of std namespace in your code first, so you can remove the std:: clauses.
using namespace std;
cin.clear() and cin.sync() are not necessary, just use cin.ignore() after input a integer type and before input a char type
cin >> nv.ID;
cin.ignore();
gets_s(nv.name);
see this post to understand it better
you are collecting char s[20]; from input in some lines. Why?? remove it
in this example and using operators for file programming ( << ) you should add a space character after writing each data to file for separate data
file << nv.ID << ' ' << nv.name
standard functions for input or print char type are gets() and puts(), but you use gets_s() that I think it's because of secure warning, you can disable this error, In this case, if you want your code to use another compiler it will not be a problem. You can only comment one line instead of change many lines
#pragma warning(disable: 4996)

Using user input to define array

I have a project where I need to create a shopping list with checkout functionality. I am trying to create an array using a users input. They supply how many products they are purchasing and I need to use that to define the size of the array.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct shopList {
double pluCode;
string product;
int saleType; // 0 = per unit, 1 = per pound
double price;
double inventory;
};
int main(){
char line[255];
const int items = 0;
int n;
ofstream outfile;
outfile.open("products.txt");
cout << "How many items in your checkout: ";
cin >> items;
shopList shop[items];
for (n = 0; n < items; n++) {
cout << "Enter the PLU code: ";
cin >> shop.pluCode;
outfile << shop.pluCode << " ";
cout << "Enter product name: ";
cin >> shop.product;
outfile << shop.product << " ";
cout << "Enter the price type (0 for per unit, 1 for per pound): ";
cin >> shop.saleType;
outfile << shop.saleType << " ";
cout << "Enter the price of the product: ";
cin >> shop.price;
outfile << shop.price << " ";
cout << "How much will you purchase: ";
cin >> shop.inventory;
outfile << shop.inventory << " " << "\n";
}
outfile.close();
ifstream infile;
infile.open("products.txt");
infile.getline(line, 255);
cout << line << endl;
}
It's possible , you just have to change your declaration like that;
int items = 0 ;
cin >> items;
shopList *shop = new shopList [items];

C++ pointer runtime error

I made a program using structure and pointer. But for some reason it is not working properly. The main problem is that, for-loop would no go as it would. It would be helpful if you could solve this problem
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
struct Book{
string name;
int release;
};
int main(){
//local variable
int i;
string release_dte;
int choice;
//interface
cout << "Welcome to Book Storage CPP" << endl;
cout << "How many entries would you like to make: ";
cin >> choice;
Book* Issue = new Book[choice];
//for handler
for (i = 0; i < choice; i++){
cout << "Book: ";
getline(cin, Issue[i].name);
cout << "Release Date: ";
getline(cin, release_dte);
Issue[i].release = atoi(release_dte.c_str());
}
cout << "These are your books" << endl;
for ( i = 0; i < choice; i++){
cout << "Book: " << Issue[i].name << " Release Date: " << Issue[i].release << endl;
}
system("pause");
return 0;
}
You're not checking if the input succeeded, nor are you clearing the new line left after the extraction into choice:
if ((std::cout << "Book: "),
std::getline(std::cin >> std::ws, Input[i].name) &&
(std::cout << "Release Date: "),
std::getline(std::cin >> std::ws, release_dte))
{
Input[i].release = std::stoi(release_dte);
}
You should also be using std::stoi for C++ strings as shown above.
I could not exactly infer what is the problem you are referring to. But my guess is getline() function inside the for loop is not working properly, I suggest the code before the for loop to be like the following\
cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
for (i = 0; i < choice; i++){
cout << "Book: ";
getline(cin, Issue[i].name);
cout << "Release Date: ";
getline(cin, release_dte);
Issue[i].release = atoi(release_dte.c_str());
}
Your final code should be
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
struct Book{
string name;
int release;
};
int main(){
//local variable
int i;
string release_dte;
int choice;
//interface
cout << "Welcome to Book Storage CPP" << endl;
cout << "How many entries would you like to make: ";
cin >> choice;
Book* Issue = new Book[choice];
cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
//for handler
for (i = 0; i < choice; i++){
cout << "Book: ";
getline(cin, Issue[i].name);
cout << "Release Date: ";
getline(cin, release_dte);
Issue[i].release = atoi(release_dte.c_str());
}
cout << "These are your books" << endl;
for ( i = 0; i < choice; i++){
cout << "Book: " << Issue[i].name << " Release Date: " << Issue[i].release << endl;
}
system("pause");
return 0;
}
This will work as you intended