【问题标题】:Why my string value store all char arrays from my struct?为什么我的字符串值存储结构中的所有字符数组?
【发布时间】:2020-07-18 19:16:54
【问题描述】:

我正在读取包含此数据的文件:

0001 Howard      Paredes Zegarra     Computacion    
0002 Penny       Vargas Cordero      Industrial     
0003 Sheldon     Cooper Quizpe       Mecatronica    

我的 cpp 文件是这样的:

struct Alumno {
    char    codigo[5];
    char    nombre[12];
    char    apellidos[20];
    char    carrera[15];
};


istream& operator >> (istream &stream, Alumno &record)
{   stream.read(record.codigo, 5);
    stream.read(record.nombre, 12);
    stream.read(record.apellidos, 20);
    stream.read(record.carrera, 15);
    stream.get();
    return (stream);
}



vector<Alumno> load() {
    ifstream file("datos.txt");
    vector<Alumno> students;

    while (!file.eof()) {
        Alumno student = Alumno();
        file >> student;
        students.push_back(student);
    }

    file.close();
    return (students);
}

int main() {
    auto students = load();

    for (auto student : students) {
        string nombre = student.nombre;
        cout << nombre << endl;
    }

    return (0);
}

所以问题是当打印变量“nombre”时打印整行减去第一列。 预期输出:

Howard
Penny
Sheldon

但是当前的输出是:

Howard      Paredes Zegarra     Computacion    
Penny       Vargas Cordero      Industrial     
Sheldon     Cooper Quizpe       Mecatronica 

为什么我有这个输出,我的结构中的指针字符是否有问题,任何建议都会很棒。提前致谢。 注意:我不能在这个任务中使用字符串。

【问题讨论】:

    标签: c++ char fstream iostream


    【解决方案1】:

    由于您使用的是 C 风格的字符串,因此您需要在插入数组的 chars 之后添加一个空终止符。这意味着您需要将每个 char 数组的大小增加一。否则当你输出时,它会在你告诉它打印的数组之后继续显示所有数组的字符。

    由于不允许使用 std::string,因此请在 C 样式字符串的末尾附加一个空终止符(数字 0 或字符 '\0')。

    【讨论】:

    • 非常感谢,我必须复习 C 样式字符串的主题。
    猜你喜欢
    • 2020-07-26
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 2015-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多