0

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();
    }
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • Welcome! Please format your code (indent it consistently) if you want people to read it and understand its structure. As a new user here, also take the [tour] and read [ask]. – Ulrich Eckhardt Jun 20 '20 at 07:36
  • `file.open("Student" + std::to_string(i) + ".txt")` is probably what you wanted. – Ruks Jun 20 '20 at 07:36
  • BTW, you don't need `file.close();` at the end there. The file is automatically closed at the end of scope. Automatic storage duration objects in loop body live for one iteration only. – jvd Jun 20 '20 at 07:50
  • Unrelated but good to read: [Why is `using namespace std;` considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Ted Lyngmo Jun 20 '20 at 08:13
  • This doesn't address the question, but get in the habit of initializing objects with meaningful values rather than default-initializing them and immediately overwriting the default values. In this case that means changing `ofstream file; file.open(whatever);` to `ofstream file(whatever);`. And you don't need to call `file.close();`. The destructor will do that. Yes, the `file` object gets destroyed at the end of the block, **each time** through the loop; that's because it gets constructed each time through the loop as well. – Pete Becker Jun 20 '20 at 12:24

1 Answers1

3

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;
    }
}
brc-dd
  • 10,788
  • 3
  • 47
  • 67