How to write a program in C++ which creates a file “grade.txt” and stores student’s grade and name.

Dani AI

Generated

A compact, practical answer that builds on and 's pointers and gives a safe, ready-to-run example for . The snippet below creates (or appends to) a text file named "grade.txt", accepts a full student name (spaces allowed) and a numeric grade, and stores each record as a simple pipe-delimited line. Basic error checking and an append mode example are included so existing data is not overwritten.

#include <iostream>
#include <fstream>
#include <string>

int main() {
    std::string name;
    int grade;

    std::cout << "Student name: ";
    std::getline(std::cin, name);
    std::cout << "Grade (0-100): ";
    if (!(std::cin >> grade)) return 1;

    std::ofstream out("grade.txt", std::ios::app);
    if (!out) {
        std::cerr << "Failed to open grade.txt\n";
        return 1;
    }

    out << name << '|' << grade << '\n';
    return 0;
}

Notes and quick troubleshooting: the std::ios::app mode appends instead of truncating the file; omit it to overwrite. The file is created in the program's working directory (IDEs often use the build/debug folder). Use std::getline so full names are captured. Choose a delimiter that will not appear in names (pipe | is simple); for robust interchange use CSV with proper quoting or a small database (SQLite) if records grow. Always check the stream state (if(!out)) to catch permission or path errors. As suggested, trying the code and inspecting the created file is the fastest way to learn the details.

Recommended Answers

All 3 Replies

Using fstream I think?

These things are easily available from the internet, i guess you know about google.Keep the forum for asking things beyond your understanding.Try coding, if there are any issues then ask.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.