Concept
How can you convert a Student structure into a string?
ComputerScienceOne / To String Functions
"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;"
Related Ideas
- How can StringBuilder be used to format a name?ComputerScienceOne · Arrays of Strings
- How can strings be created and assigned to variables?ComputerScienceOne · Basic Operations
- How do functions work in programming languages?ComputerScienceOne · Functions
- How do you pass an array of structures to a function to compute an average GPA?ComputerScienceOne · Passing Arrays of Structures
- How do you call functions in C?ComputerScienceOne · Organizing Functions