如何在c++中编写多字符文字到文件?



我有一个具有不同数据类型的对象结构定义数组,我试图将内容写入文件,但其中一个字符值多于一个字符,并且它只将多字符字面量中的最后一个字符写入文件。字符中的值是'A-',但只写了-。有可能把它全部写下来吗?在任何人建议使用字符串之前,我需要为Grade使用char数据类型。

我的代码是这样的:

//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;
}

文本文件最后显示如下:

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

不可能在单个字节char中容纳两个字符。最简单的解决方案是修改数据结构:

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

然后,你必须把A-放在双引号里,像这样:

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

最新更新