【发布时间】:2022-11-23 14:37:21
【问题描述】:
我有一个结构定义的具有不同数据类型的对象数组,我试图将内容写入文件,但其中一个 char 值超过一个字符,并且它只将多字符文字中的最后一个字符写入文件. char 中的值为“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
【问题讨论】:
-
多字符文字是
ints,而不是chars。您不能将两个字符放入一个char。 -
'A-'不能存储在studentInfo::Grade中,只能是单个字符。