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 do sscanf() and sprintf() work with strings?ComputerScienceOne · Tokenizing
- How can the toString() method represent a Java object?ComputerScienceOne · Common Methods
- What does the completed PHP Student class look like?ComputerScienceOne · Example
- How do you access members through a pointer to a structure?ComputerScienceOne · Selection Operators
- How can you create static strings with character arrays?ComputerScienceOne · Character Arrays
- How can strlen determine the length of a C string?ComputerScienceOne · String Library
- How can StringBuilder be used to format a name?ComputerScienceOne · Arrays of Strings
- How do you access members of a statically declared structure?ComputerScienceOne · Selection Operators