Bifalgorithm post · Computer science one · To String Functions

How can you convert a Student structure into a string?

How can you convert a Student structure into a string? (Computer science one · To String Functions) — "23.4.2. To String Functions\n\nAnother common operation…

Ideas in this flowchart

  • Fonctions de conversion en chaîne pour les structures
  • Représenter les données d’une structure sous forme de chaîne lisible
  • Une fonction pourrait afficher directement les membres avec printf()
  • Une fonction générale peut retourner la représentation sous forme de chaîne
  • La chaîne retournée peut être affichée ou écrite dans un fichier
  • La longueur nécessaire varie selon l’instance de la structure
  • Calculer d’abord la longueur nécessaire selon le format choisi
  • La longueur comprend les noms, les chiffres de l’identifiant, le GPA et les caractères de formatage
  • Allouer un espace mémoire de n caractères avec malloc()
  • Remplir la chaîne avec sprintf() selon le format défini
  • Retourner la chaîne représentant la structure Student
Feed/

How can you convert a Student structure into a string?

No cover

Channel

Computer science one

1 page

"23.4.2. To String Functions\n\nAnother common operation with structures is to output their data as a human-readable string representation. We could write a function that output a structure’s member variables to the standard output using printf(). However, it would more useful if we created a general function that returned a string representation of the structure. That way, we could decide what to do with the string: output it to the standard output, to a file, etc. Not all structure instances will require the same length string. Some students for example may have long names, while others have short. We can handle this by first calculating the length of the string necessary for whatever formatting we’ve chosen.\n\n/**\n\n* Returns a string representation of the given\n\n* Student structure.\n\n*/\n\nchar * studentToString(const Student *s) {\n\nint n = strlen(s->firstName) +\n\nstrlen(s->lastName) +\n\n8 + //id, assumed to always be at most 8 digits\n\n4 + //gpa, assumed to be 0.0 - 4.0\n\n19; //other formatting characters\n\nchar *str = (char *) malloc(sizeof(char) * n);\n\nsprintf(str, \"%s, %s, ID = %d (GPA = %.2f)\",\n\ns->lastName, s->firstName, s->id, s->gpa);\n\nreturn str;"

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.