简体   繁体   中英

How to write a multicharacter literal to a file in C++?

I have a structure defined array of objects with different data types, I'm trying to write the contents to a file but one of the char values is more than one character, and it's only writing the last character in the multicharacter literal to the file. The value in the char is 'A-', but only - is getting written. Is it possible to write the entirety of it? Before anybody suggests just using a string, I am required to use the char data type for Grade.

The code I have looks like this:

//Assignment12Program1
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;

//Structure with student info
struct studentInfo   
{
    char Name[100];
    int Age;
    double GPA;
    char Grade;
};

//Main function
int main() {
    //Sets number of students in manually made array
    const int NUM_STUDENTS = 4;
    //Array with students created by me
    studentInfo students[NUM_STUDENTS] = { 
        {"Jake", 23, 3.45, 'A-'},
        {"Erica", 22, 3.14, 'B'},
        {"Clay", 21, 2.80, 'C'},
        {"Andrew", 18, 4.00, 'A'}
    };

    //defines datafile object
    fstream dataFile;
    //Opens file for writing
    dataFile.open("studentsOutput.txt", ios::out);
    //Loop to write each student in the array to the file
    for (int i = 0; i < 4; i++) {
        dataFile << students[i].Age << " " << setprecision(3) << fixed << students[i].GPA << " " << students[i].Grade << " " << students[i].Name << "\n";
    }
    dataFile.close();

    return 0;
}

And the text file ends up displaying this:

23 3.450 - Jake
22 3.140 B Erica
21 2.800 C Clay
18 4.000 A Andrew

It is not possible to fit two characters in a single byte char . The simplest solution is to modify the data structure:

struct studentInfo {
    .
    .
    char Grade[3]; // +1 for a null-terminator
};

Then, you have to place A- in double-quotes like this:

studentInfo students[NUM_STUDENTS] = {
    { "Jake", 23, 3.45, "A-" },
    { "Erica", 22, 3.14, 'B' },
    { "Clay", 21, 2.80, 'C' },
    { "Andrew", 18, 4.00, 'A' }
};

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM