【问题标题】:How to write a multicharacter literal to a file in C++?如何在 C++ 中将多字符文字写入文件?
【发布时间】: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中,只能是单个字符。

标签: c++ char fstream


【解决方案1】:

不可能在单个字节中容纳两个字符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' }
};

【讨论】:

    猜你喜欢
    • 2021-03-04
    • 2015-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-06
    相关资源
    最近更新 更多